我制作了一张小 map ,我称之为 BMW
.它包含 key Usage
和 Diesel
,如下图。
#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;
}
我想做的是找到 key Usage
在 map 中,然后打印出包含 Usage
值的字符串(1, 2)。我尝试使用的代码不起作用,我无法在 Stackoverflow 上找到好的答案。这是我得到的错误:
error: no matching function for call to '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)'|
如果我想只获取其中一个字符串,比如第一个字符串,那就太好了。
(稍后在适当的时候将字符串转换为 int,但由于技术原因,我现在想将它们作为字符串读取)
最佳答案
BMW.find('Usage')->second
// ^ ^
这些是单引号。
单引号分隔 char
文字。
你想要双引号。
那是因为双引号分隔了 string 文字。
错误消息说您正在尝试使用不存在的 find(int)
重载的原因是 char
文字实际上有多个其中的字符是一种特殊的东西,称为“多字 rune 字”,属于 int
类型和实现定义的值。您通常不打算使用这些。
接下来,您将遇到一个问题,即元组没有内置的 cout
格式。您将必须使用 BMW.find("Usage")->second
并将其提供给某个函数,以您想要的任何方式打印内容。
关于c++ - 使用 std::tuple 从 map 中输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58301843/