effective STL 读书笔记 二

来源:互联网 发布:地图数据质量 编辑:程序博客网 时间:2024/05/22 21:10

第九条:慎重选择删除元素的方法。


1. 对于一个连续内存的容器(vector , deque, string)最好的办法是使用 erase - remove

   c.erase(remove(c.begin(), c.end(), 1963), c.end());


2. 对list,这一办法同样适用,但是第44条指出,list的成员函数remove更加有效

c.remove(1963)



3.对关联容器怎么删除特定值元素呢。(set , map)

map ,set 删除会使当前迭代器失效,

map<int, string> mapIntStrColl;
map<int, string> ::iterator itor = mapIntStrColl.begin();


for (int i =0; i< 1; ++i)
{
mapIntStrColl.insert(make_pair(1,"s"));
mapIntStrColl.insert(make_pair(2,"s"));
mapIntStrColl.insert(make_pair(3,"s"));
mapIntStrColl.insert(make_pair(4,"s"));
mapIntStrColl.insert(make_pair(5,"s"));
mapIntStrColl.insert(make_pair(6,"s"));
}
for (itor = mapIntStrColl.begin(); itor != mapIntStrColl.end(); )
{
if (itor->first == 1)
{
mapIntStrColl.erase(itor++);
}
else{
++itor;
}



}


for(itor = mapIntStrColl.begin(); itor != mapIntStrColl.end(); ++ itor)
{
cout << itor->first << " "<<(itor->second).c_str() << endl;
}


4. 对于序列容器的删除。删除的时候不仅会使当前迭代器失效也回使以后迭代器失效。故

vector<int> VectorIntColl;
vector<int> ::iterator itor;
for (int i = 0 ; i< 10 ; ++ i)
{
VectorIntColl.push_back(i);
}
    
for (itor = VectorIntColl.begin(); itor != VectorIntColl.end();  )
{
if (*itor == 7)
{
itor=VectorIntColl.erase(itor);
}
else
++ itor;
}
for (itor = VectorIntColl.begin(); itor != VectorIntColl.end(); ++ itor)
{
cout <<  *itor << endl;
}

原创粉丝点击