STL—vector删除重复元素

删除重复元素 需要用两个STL算法排序sort  排重unique

unique的作用是从输入序列中“删除”所有相邻的重复元素。  这个“删除”不是真正的删除,只是做内容调整了

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int main()
{
    vector<int> vInt;
    vInt.push_back(2);
    vInt.push_back(5);
    vInt.push_back(1);
    vInt.push_back(2);
    vInt.push_back(5);
    vInt.push_back(1);
    cout << "未排序:unique 偏移量";
    cout << unique(vInt.begin(),vInt.end()) - vInt.begin() << endl;
    for (int i=0; i<vInt.size(); i++) {
        cout << vInt[i] << " ";
    }
    cout << endl;
    sort(vInt.begin(), vInt.end(), less<int>());
    cout << "*****排序unique前*******" << endl;
    for (int i=0; i<vInt.size(); i++) {
        cout << vInt[i] << " ";
    }
    cout << endl;
    cout << "排序:unique 偏移量";
    cout << unique(vInt.begin(),vInt.end()) - vInt.begin() << endl;
    cout << "*****排序unique后*******" << endl;
    for (int i=0; i<vInt.size(); i++) {
        cout << vInt[i] << " ";
    }
    cout << endl;
    return 0;
}
结果:

未排序:unique 偏移量6

2 5 1 2 5 1 

*****排序unique*******

1 1 2 2 5 5 

排序:unique 偏移量3

*****排序unique*******

1 2 5 2 5 5 


第一次unique返回值  vInt.begin()+6 也就是 vInt.end();表明未找到相邻元素重复的

对vector 排序后 的再次unique 

从前后的元素可以看出  vector 的容量不变,内容被做调整,从偏移量3 可以知道

1 2 5 为去除重复元素后的序列  而 2 5 5 为多余的
unique 算法:

// unique

template <class _ForwardIterator, class _BinaryPredicate>
_ForwardIterator
unique(_ForwardIterator __first, _ForwardIterator __last, _BinaryPredicate __pred)
{
    __first = _VSTD::adjacent_find<_ForwardIterator, typename add_lvalue_reference<_BinaryPredicate>::type>
                                 (__first, __last, __pred);
    if (__first != __last)
    {
        // ...  a  a  ?  ...
        //      f     i
        _ForwardIterator __i = __first;
        for (++__i; ++__i != __last;)
            if (!__pred(*__first, *__i))
                *++__first = _VSTD::move(*__i);
        ++__first;
    }
    return __first;
}

要删除重复元素  结合erase函数 

    iterator erase(const_iterator __first,const_iterator __last);区域删除

上面 第二次unique  语句更改成

    vInt.erase(unique(vInt.begin(),vInt.end()), vInt.end()); 即可实现对vInt去除重复的

得到 1 2 5

如果vector中存储的元素是自定义类型,

unique算法需要重载"=="操作符。

sort  需要默认重载<

sort(first,end,less<type>())  less 对应 <  

greater 对应 > 

 


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值