地图<字符串 ,字符串>如何在此地图中插入数据?字符串>
我需要以键值格式存储字符串。所以我使用如下所示的地图。
#include<map>
using namespace std;
int main()
{
map<string, string> m;
string s1 = "1";
string v1 = "A";
m.insert(pair<string, string>(s1, v1)); //Error
}
插入行出现以下错误
错误 C2784: 'bool std::operator <(const std::_Tree<_Traits> &,const std::_Tree<_Traits> &)' :无法推导出 'const std:: 的模板参数_树<_特征> &'来自 'const std::string'
我尝试了 make_pair 函数也如下所示,但这也报告了相同的错误。
m.insert(make_pair(s1, v1));
请让我知道出了什么问题以及上述问题的解决方案是什么。 解决上述问题后,我可以使用如下所示的方法来根据键检索值吗
m.find(s1);
I need to store strings in key value format. So am using Map like below.
#include<map>
using namespace std;
int main()
{
map<string, string> m;
string s1 = "1";
string v1 = "A";
m.insert(pair<string, string>(s1, v1)); //Error
}
Am getting below error at insert line
error C2784: 'bool std::operator <(const std::_Tree<_Traits> &,const std::_Tree<_Traits> &)' : could not deduce template argument for 'const std::_Tree<_Traits> &' from 'const std::string'
I tried make_pair function also like below, but that too reports the same error.
m.insert(make_pair(s1, v1));
Pls let me know what's wrong and what's the solution for above problem.
After solving above problem, can i use like below to retrieve value based on key
m.find(s1);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
您可以尝试一下吗:
编译器似乎不知道如何比较字符串。也许她对字符串还不够了解,但过于关注您的
地图
而无法弄清楚 ATM。Could you try this:
It seems the compiler doesn't know how to compare strings. Maybe she doesn't know enough about strings yet, but is too focused on your
map
to figure that out ATM.这里是设置地图的方法<...,...>
Here is the way to set up map<...,...>
尝试使用
m[s1] = v1;
代替。Try
m[s1] = v1;
instead.现在,您有多种可能性如何以键值格式存储字符串:
并在 c++11 中遍历它:
You have several possibilities how store strings in key value format now:
And traverse it in c++11:
我认为这与
不包含
而是包含
的事实有关。当您向地图添加元素时,需要通过排序找到地图中的正确位置。排序时,map 会尝试定位运算符<
,从中找到新元素的正确位置。但是,
中没有用于定义字符串的运算符 <
,因此您会收到错误消息。I think it has to do with the fact that
<map>
doesn't include<string>
, but<xstring>
. When you are adding elements to the map it needs to find the correct position in the map by sorting. When sorting, map tries to locate theoperator <
, from which it finds the correct location for the new element. However, there is nooperator <
for the definition of string in<xstring>
, thus you get the error message.s1 是一个您希望作为字符串传递的整数...这可能是错误的主要原因!
The s1 is an integer you are hoping pass as string...thats likely the main cause of the error!!
我认为您在某处错过了
#include
。I think you miss a
#include <string>
somewhere.