// 目的:演示学习一下标准库
//
//知识注意点:
//更易型算法(指那些会移除 remove, 重排resort, 修改 modify 元素的算法)用于关联式容器
//身上会出问题。
//关联式容器不能被当作操作目标,原因很简单:如果更易型算法用于关联式容器身上,会改变某位置
//上的值,进而破坏其已序(sorted)特性,我就推翻了关联式容器的基本准则; 容器内的元素总是
//根据某个排序准则自动排序。因此,为了保证这个原则,关联式容器的所有迭代器地均被声明为指向
//常量。如果你更易关联式容器中的元素,会导致编译错误。 --《C++标准程序库》p115
#include "stdafx.h"
#include <iostream>
#include <map>
#include <string>
#include <algorithm>
#include <sstream> // for stringstream
using namespace std;
typedef std::map<std::string, int> StringIntMap;
int _tmain(int argc, _TCHAR* argv[])
{
StringIntMap coll;
StringIntMap::iterator pos;
// 初始化容器
for (int i = 0; i < 10; ++i)
{
int num = i;
if (i > 4)
{
num -= 5;
}
stringstream ss;
ss << "benben_" << i;
string sKey = ss.str();
coll.insert(make_pair(sKey, num));
}
int value = 2; // 这里随便指定一个要删除的值
#if 1
// 移除容器中的所有特定值的元素
// 方法一: 此方法可行
for (pos = coll.begin(); pos != coll.end(); NULL)
{
if (pos->second == value)
{
coll.erase(pos++);
}
else
{
++pos;
}
}
#elif 0
// 方法二: 这个方法是错误的。如果只移除第一个发现的元素在erase语句后加 break; 倒是也可
for (pos = coll.begin(); pos != coll.end(); ++pos)
{
if (pos->second == value)
{
coll.erase(pos);
// 注意: 上一句调用之后,pos 迭代器已经失效,然后再在for 循环体中的++pos,运行期就直接出错了
// break; //若在这里加上这一句,就只删到第一个找到的元素
}
}
#else
// 方法三: 注意这个编译都通不过,详情见最前面的 知识点
remove(coll.begin(), coll.end(), value);
#endif
return 0;
}
关联式容器移除元素易错了点, 实例map 学习
最新推荐文章于 2024-05-20 09:00:00 发布