最近工作中用到STL中的map,由于map的值是new出来的地址空间,所以牵涉到删除map键值对及释放空间的问题,自己做了几个小测试,记录在下。
//创建并初始化 map 容器
map<std::string, std::string*>myMap;
string *s1 = new string("http://c.biancheng.net/c/");
string *s2 = new string("http://c.biancheng.net/python/");
string *s3 = new string("http://c.biancheng.net/stl/");
myMap["C语言教程"] = s1;
myMap["python语言教程"] = s2;
myMap["stl语言教程"] = s3;
cout <<endl;
//输出myMap容器存储键值对的个数
cout <<"myMap size = " << myMap.size() << endl;
//输出Python字段内容
cout <<"1-Python教程 is " << *s2 << endl;
cout <<"myMap中的Python教程 is " << *myMap["python语言教程"] << endl;
//删除 myMap 容器键为 "Python教程" 的键值对
int num = myMap.erase("python语言教程");
//输出 myMap 容器中剩余键值对的数量
cout << "new myMap size = " << myMap.size() << endl;
//输出 erase() 方法的返回值
cout << "num = " << num << endl;
//再次输出Python字段内容
cout << "2-Python教程 is " << *s2 << endl;
cout << "3-Python教程 is " << *s2 << endl;
cout << "4-Python教程 is " << *s2 << endl;
输出:
myMap size = 3
1-Python教程 is http://c.biancheng.net/python/
myMap中的Python教程 is http://c.biancheng.net/python/
new myMap size = 2
num = 1
2-Python教程 is http://c.biancheng.net/python/
3-Python教程 is http://c.biancheng.net/python/
4-Python教程 is http://c.biancheng.net/python/
cout <<endl;
//输出myMap容器存储键值对的个数
cout <<"myMap size = " << myMap.size() << endl;
//输出Python字段内容
cout <<"1-Python教程 is " << *s2 << endl;
delete s2;
cout <<"myMap中的Python教程 is " << *myMap["python语言教程"] << endl;
//删除 myMap 容器键为 "Python教程" 的键值对
int num = myMap.erase("python语言教程");
//输出 myMap 容器中剩余键值对的数量
cout << "new myMap size = " << myMap.size() << endl;
//输出 erase() 方法的返回值
cout << "num = " << num << endl;
//再次输出Python字段内容
cout << "2-Python教程 is " << *s2 << endl;
cout << "3-Python教程 is " << *s2 << endl;
cout << "4-Python教程 is " << *s2 << endl;
如果增加上面红色的一行,删除s2的内存空间,则输出如下:
myMap size = 3
1-Python教程 is http://c.biancheng.net/python/
myMap中的Python教程 is 1.bianc
new myMap size = 2
num = 1
2-Python教程 is 1.bianc
3-Python教程 is 1.bianc
4-Python教程 is 1.bianc
可见,本来完整的一个网址遭到了破坏,变成了“is 1.bianc”。注意:这个删除是在map容器erase之前进行的,也就是说,delete操作并不影响map的erase操作,但是影响到了map容器中键值对的值。
cout <<endl;
//输出myMap容器存储键值对的个数
cout <<"myMap size = " << myMap.size() << endl;
//输出Python字段内容
cout <<"1-Python教程 is " << *s2 << endl;
cout <<"myMap中的Python教程 is " << *myMap["python语言教程"] << endl;
//删除 myMap 容器键为 "Python教程" 的键值对
int num = myMap.erase("python语言教程");
//输出 myMap 容器中剩余键值对的数量
cout << "new myMap size = " << myMap.size() << endl;
//输出 erase() 方法的返回值
cout << "num = " << num << endl;
delete s2;
//再次输出Python字段内容
cout << "2-Python教程 is " << *s2 << endl;
cout << "3-Python教程 is " << *s2 << endl;
cout << "4-Python教程 is " << *s2 << endl;
输出:
myMap size = 3
1-Python教程 is http://c.biancheng.net/python/
myMap中的Python教程 is http://c.biancheng.net/python/
new myMap size = 2
num = 1
2-Python教程 is 1.bianc
3-Python教程 is 1.bianc
4-Python教程 is 1.bianc
这个删除是在map容器erase之后进行的。实际开发中,建议按照下面的顺序。
delete s2;
S2 = nullptr;
int num = myMap.erase("python语言教程");