从带有std :: tuple的地图中退出 [英] Cout from a map with std::tuple

查看:113
本文介绍了从带有std :: tuple的地图中退出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我制作了一张小地图,称为宝马。它包含键用法柴油,如下所示。

I have made a small map that I call BMW. It contains the keys Usage and Diesel, as shown below.

#include <iostream>
#include <bits/stdc++.h>
#include <map>
#include <vector>
using namespace std;

int main()
{

    // initialize container
    std::map<string, std::tuple<string, string>> BMW;

    // insert elements
    BMW.insert({"Usage", {"1", "2"}});
    BMW.insert({"Disel", {"2", "3"}});

    std::cout << "Usage => " << BMW.find('Usage')->second << '\n';

    return 0;
}

我要做的是找到键用法,然后打印出包含用法(1、2)值的字符串。我尝试过的代码无法正常工作,我无法在Stackoverflow上找到一个很好的答案。这是我得到的错误:

What I want to do is to find the key Usage in the map and then print out the strings containing the values for Usage(1, 2). The code I tried with does not work and I am not able to find a good answer why here on Stackoverflow. Here is the error I get:

错误:没有匹配的函数可以调用'std :: map< std :: __ cxx11 :: basic_string< char>,std :: tuple< std :: __ cxx11 :: basic_string< char,std :: char_traits< char>,std :: allocator< char> >,std :: __ cxx11 :: basic_string< char,std :: char_traits< char>,std :: allocator< char> > > > :: find(int)'|

如果我只能获得其中一个字符串,那将是很棒的,例如第一个,如果我想这样做。

It would be great if I could be able to get only one of the strings, like the first one, if I want to do that.

(稍后,在适当的情况下,字符串将被转换为int,但是由于技术原因,我想阅读它们

(the strings will later be converted to int when this is appropriate, but because of technical reasons I want to read them as strings for now)

推荐答案

BMW.find('Usage')->second
//       ^     ^

这些是单引号

单引号分隔 char 文字。

您想要双引号

这是因为双引号分隔了 string 文字。

That's because double quotes delimit string literals.

错误消息的原因是您试图使用不存在的 find(int)重载,是实际上包含多个字符的 char 文字是一种特殊的东西,称为多字符文字,它是 int 类型和实现定义的值。您通常不打算使用这些。

The reason the error message says you're trying to use the non-existent find(int) overload, is that a char literal that actually has more than one character in it is a special thing called a "multi-character literal", of int type and implementation-defined value. You usually don't intend to use these.

接下来,您将遇到以下问题:元组没有内置的 cout 格式。您将必须花费 BMW.find( Usage)-> second 并将其提供给某个函数,该函数可以按照您想要的任何方式打印内容。

Next, you're going to run into the problem that there is no built-in cout formatting for a tuple. You will have to take BMW.find("Usage")->second and give it to some function that prints the contents in whatever way you want.

这篇关于从带有std :: tuple的地图中退出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆