C++ std::map与lt之间是否存在差异;int,int>;和std::map<;常数int,int>;?

C++ std::map与lt之间是否存在差异;int,int>;和std::map<;常数int,int>;?,c++,stl,std,stdmap,C++,Stl,Std,Stdmap,据我所知,std::map中的值对中的键一旦插入就不能更改。这是否意味着创建键模板参数为const的映射无效 std::map<int, int> map1; std::map<const int, int> map2; std::map1; 地图地图2; 由于int是按值复制的,所以const的声明没有意义。 另一方面 std::map<const char*, int> map2; std::map map2; 如Dewfy所说,在您给出的示例中,

据我所知,std::map中的值对中的键一旦插入就不能更改。这是否意味着创建键模板参数为const的映射无效

std::map<int, int> map1;
std::map<const int, int> map2;
std::map1;
地图地图2;

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

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

如Dewfy所说,在您给出的示例中,它极大地改变了一幅图片,这无关紧要,因为int是一种内置类型,它将按值复制,但对于char*它有点不同

如果你有

std::map<char *, int> map;
std::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
char*y=新字符[4];
const char*x=“asdf”;
地图;
图.插入(组成一对(y,4))//好啊
图.插入(组成一对(x,4))//失败
带着

std::map<char*, int> map;
std::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'
char*x=新字符[1];
(*x)=‘a’;
迭代器it=map.begin();
coutfirst)[0]=“x”

cout
std::map
无论如何都要构造它的键类型:
std::map::value\u type
std::pair
。如果向键类型添加一个
const
const-const-int
将简单地折叠为
const-int

你的标题问题的答案是肯定的。这是有区别的。不能将
std::map
传递给接受
std::map
的函数


然而,映射的功能行为是相同的,即使它们是不同的类型。这并不罕见。在许多上下文中,int和long的行为是相同的,即使它们是形式上不同的类型。

您的示例没有处理以下问题:const char*是指向常量char的非常量指针,而问题是将类型设置为常量(因此是指向非常量char的常量指针):std::map关于使用意义的文章要点复制语义,“constchar*”按值复制,允许对键进行迭代,但禁用对键的修改。你的声明有点不方便它禁用键上的迭代,但允许修改:char*const v=“qwe”*v='6'//允许/*但这会导致编译器错误:v++;*/char*const v-justSee对Dewfy的注释:const char*是指向常量char的非常量指针。您并不是将类型设置为常量,而是完全更改类型(指向不同的类型),即实际回答问题的第一个答案。
 std::map<const char *, int>
 map<const char*, int>::iterator