标签:
#include <iostream> #include <map> using namespace std; void fun(int a[]){ a[0] = 12; } struct compare { bool operator()(const char * s1, const char * s2) const { return strcmp(s1, s2) < 0; } }; int main(){ map<char*, char*, compare> student; char id1[11] = "1395682451"; char name1[18] = "xiaoming"; student.insert(pair<char*, char*>(id1, name1)); cout << student[id1] << endl; char id2[11] = "1395682451"; char name2[18] = "lisi"; student.insert(pair<char*, char*>(id2, name2)); cout << student[id2] << endl; student[id1] = name2; cout << student[id2] << endl; map<char*, char*> teacher; teacher.insert(pair<char*, char*>(id1, name1)); teacher.insert(pair<char*, char*>(id2, name2)); cout << "teacher 1 is: " << teacher[id1] << endl; cout << "teacher 2 is: " << teacher[id2] << endl; int b[2] = { 1, 2 }; fun(b); cout << b[0] << endl; return 0; }
默认使用的是内存地址的比较,上面的teacher是使用了默认比较方式,会发现,尽管id1和id2内容完全相同,但是仍然插入成功。
student使用了字符串内容的比较,insert操作插入没有成功,因为遇到了相同字符串,所以返回,这是不会覆盖原来的值得,如果使用下标覆盖方式,原来的值会被覆盖掉。
标签:
原文地址:http://www.cnblogs.com/deepblueme/p/4582630.html