前言:
对于STL的容器删除多个重复值时,如果按(伪代码)
for(iterator itr = V.begin();itr!=V.end();itr++)
{
if(itr->id==del_value)
V.erase(itr);
}
上面的代码中,如果V中只有一个等于del_value的值,这样将正;如果是多个相同值时,这样将会得不到正确的结果!解决方法见下面(^_^,stl的发明者真是思维严密~)
1.对于vector放一般类型值时,只须:
vector<int> V;
V.push_back(3);
V.push_back(1);
V.push_back(4);
V.push_back(1);
V.push_back(5);
V.push_back(9);
copy(V.begin(), V.end(), ostream_iterator<int>(cout, " "));
// The output is "3 1 4 1 5 9".
copy(V.begin(), remove(V.begin(), V.end(), 1), ostream_iterator<int>(cout, " "));// The output is "3 4 5 9".V.erase(remove(V.begin(), V.end(), 1), V.end());
copy(V.begin(), V.end(), ostream_iterator<int>(cout, " "));// The output is "3 4 5 9".
2.对于Vector里放的是对象:
class Foo
{
int id;
Foo(int id_):id(_id){}
Foo(){};
bool operator== (const Foo& other ) const{return id==other.id;} //重载== !!!
}
vector<Foo> V;
V.push_back(Foo(3));
V.push_back(Foo(1));
V.push_back(Foo(4));
V.push_back(Foo(1));
V.push_back(Foo(5));
V.push_back(Foo(9));V.erase(remove(V.begin(), V.end(), Foo(1)), V.end()); //now the V has Foos of 3 4 5 9
3.对于其它容器可类似上面的方法
4.上帝关了你所有的门,但还是会留一扇窗你~
2544

被折叠的 条评论
为什么被折叠?



