std::map<int, int>和std::map<const int, int>之间有区别吗?

8

据我所知,在std :: map中,键值对中的键一旦插入就无法更改。这是否意味着使用const作为键模板参数创建映射没有效果?

std::map<int, int> map1;
std::map<const int, int> map2;
4个回答

13

你的标题问题的答案是肯定的。它们有所不同。你不能将std :: map <int,int>传递给接受std :: map <const int,int>的函数。

但是,尽管它们是不同类型,映射的功能行为相同。这并不罕见。在许多情况下,int和long的行为相同,即使它们形式上是不同的类型。


2
第一个真正回答问题的答案。 - Tamás Szelei

1

由于 int 是按值复制的,因此 const 的声明没有意义。 另一方面

std::map<const char*, int> map2; 

极大地改变了一张图片


1
你的示例与问题无关:const char*是指向常量字符的非常量指针,而问题涉及使类型变为常量(因此为指向非常量字符的常量指针):std::map<char* const,int>。 - David Rodríguez - dribeas
关于复制语义使用的意义,这篇文章的重点是,“const char *”按值复制,允许对键进行迭代,但禁止修改键。你的声明有些不方便——它禁止了对键的迭代,但允许修改:char *const v = "qwe"; *v = '6';//允许!!! /*但这会导致编译器错误:v++;*/char *const v - 只是 - Dewfy

1

std::map 会将其键类型设置为常量: std::map<int, int>::value_typestd::pair<const int, int>。如果您在键类型中添加一个 constconst const int 将简单地折叠为 const int


0
正如Dewfy所说,根据你提供的示例,由于int是内置类型并且将按值复制,因此没有关系,但是对于char*则有所不同...
如果您有
std::map<char *, int> map;

那么你无法插入一个声明为const char*的变量,会失败。

char * y = new char[4];
const char * x = "asdf";
std::map<char *, int> map;
map.insert(make_pair(y, 4)); //ok
map.insert(make_pair(x, 4)); //fail

带有

std::map<char*, int> map;

你可以实际说

char * x = new char[1];
(*x) = 'a';
map<char*,int>::iterator it = map.begin();
cout<<it->first; //prints 'a'
(it->first)[0] = 'x'
cout<<it->first; //prints 'x'

带有一个

 std::map<const char *, int>

你将受限于使用
 map<const char*, int>::iterator 

2
请看对Dewfy的评论:const char*是指向常量字符的非常量指针。您并没有使类型成为常量,而是完全更改了类型(以指向不同的类型)。 - David Rodríguez - dribeas

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接