地图在C++给钥匙,获取字符串
我创建地图这样的:std::map<int, std::string> mapID;
地图在C++给钥匙,获取字符串
输入:的azazaz [1] =! “串”;
我想用键打印元素是s。 例如
cout << "The string is : " << mapID.at(s)->second << endl;
OR
cout << "The string is : " << mapID.find(s)->second << endl;
但我有错误
error: no matching function for call to ‘std::map >::at(std::string&)’
UPDATE:
while(getline(file,s))
{
cout<< s << endl;
number = atoi(s.c_str());
cout << "The string is: " << mapID.at(number)<< endl;
}
如果你看看参考文献http://en.cppreference.com/w/cpp/container/map/at你会看到,方法“at”返回对的第二个元素。在你的情况是std :: string。
代码应该是
cout << "The string is : " << mapID.at(1) << endl;
是真的,但它没有解释报告的错误消息 – user463035818
错误消息解释为观察方法'at()'接收一个密钥值,所以在'std :: map
由于C++ 11,.at()
返回到与密钥k标识的元素的映射值的引用。
你的例子很好,如果你使用迭代器,然后你可以访问你的地图所做的pair元素。
这里是一个迭代
auto it = mapID.find(1);
cout << "The string is : " << it->second << endl;
或与.at()
cout << "The string is : " << mapID.at(1) << endl;
但要注意的是.AT()将抛出一个例子,如果该元素是不是在你的地图发现,因为它可以” t创建它像[]
运营商
假设OP得到错误信息报告,他们仍然会收到与此“修复”相同的错误消息。 (顺便说一句同样适用于其他“答案”)。当问题根本不清楚时,用什么来回答问题? – user463035818
@ tobi303 _“什么是冲的点”_ FGITW,因为它曾经是:P ... – user0042
@ tobi303他调用 - >第二个在std :: string元素而不是迭代器,这是他的错误,我解释它在我的回答中 – rak007
请显示[mcve]。 '1'显然不是一个字符串,所以有些东西是可疑的,但我们需要看到更多的代码来重现问题 – user463035818
如果mapID [1]不存在,它将在1处创建一个元素 – rak007
您列出的代码不能产生给定的错误信息。请向我们展示实际的代码或实际的错误消息。 (最好是我们可以剪切并粘贴到(例如)cpp.sh中的[mcve]) –