[英]Cout from a map with std::tuple
我做了一个小的 map,我称之为BMW
。 它包含键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;
}
我要做的是在 map 中找到关键的Usage
,然后打印出包含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
文字。
你想要双引号。
那是因为双引号分隔字符串文字。
错误消息说您正在尝试使用不存在的find(int)
重载的原因是,实际上包含多个字符的char
文字是一种特殊的东西,称为“多字符文字”, int
类型和实现定义的值。 您通常不打算使用这些。
接下来,您将遇到元组没有内置cout
格式的问题。 您将不得不接受BMW.find("Usage")->second
并将其提供给 function 以您想要的任何方式打印内容。
对于初学者,如果您使用成员 function find
,那么您应该检查是否确实找到了数据。
在这个表达式中
BMW.find('Usage')
您正在使用多字节字符文字而不是字符串文字。 表达式必须写成
BMW.find( "Usage" )
对于std::tuple
类型的 object 没有运算符 <<。 您必须 output 元组的单个数据成员。 这是一个演示程序。
#include <iostream>
#include <string>
#include <tuple>
#include <map>
#include <iterator>
int main()
{
std::map<std::string, std::tuple<std::string, std::string>> BMW;
// insert elements
BMW.insert( { "Usage", { "1", "2" } } );
BMW.insert( { "Disel", { "2", "3" } } );
auto it = BMW.find( "Usage" );
if ( it != std::end( BMW ) )
{
std::cout << "Usage => ( " << std::get<0>( it->second ) << ", " << std::get<1>( it->second ) << " )\n";
}
}
它的 output 是
Usage => ( 1, 2 )
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.