c++ map<string,int>和map<int,string>之间的差别?

C++语言 码拜 9年前 (2015-05-11) 2316次浏览 0个评论

有如下代码:

#include <iostream>
#include<map>
using std::map;
using namespace  std;

int _tmain(int argc, _TCHAR* argv[])
{
	//[1]
 	map<int,string> maplive;
 	maplive[1] = "";

	//[2]
	map<string,int> maplive1;
	maplive1["1"] = 10;

	return 0;
}

第二个报错:
1>c:\program files\microsoft visual studio 10.0\vc\include\xfunctional(125): error C2784: “bool std::operator <(const std::_Tree<_Traits> &,const std::_Tree<_Traits> &)”: 未能从“const std::string”为“const std::_Tree<_Traits> &”推导 模板 参数
我知道这肯定是类型推导的问题,但是为什么第一个不抱错 呢,想不通?

代码头部加上
#include<string>就是正确的

5分
作为Key的才需要用到具体函数吧
Value只是纯粹的储存而已
20分
stl map的实现是红黑数 查找默认使用小于号需要重载小于号 operator<不在xstring定义
15分
当key不能比较大小写,要自己重写key比较大小的方式。
copy了你的代码调试了一下,发现在没有#include <string>的情况下应该是根据<xstring>来实例化string对象,<xstring>是间接包含在<map>中的,<xstring>中重载的<操作符跟<string>中重载的<操作符是不一样的,所以第二个会报错

map中的key是需要支持比较操作符的,所以仅仅是#include <map>的话,string对象是不能作为map中的key的


CodeBye 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明c++ map<string,int>和map<int,string>之间的差别?
喜欢 (0)
[1034331897@qq.com]
分享 (0)

文章评论已关闭!