C++ STL Vector(容器) 如何有效一次性删除多个重复值?

前言:

对于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.上帝关了你所有的门,但还是会留一扇窗你~

 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值