删除vector中重复元素

算法unique能够移除重复的元素。每当在[first, last]内遇到有重复的元素群,它便移除该元素群中第一个以后的所有元素。

注意:unique只移除相邻的重复元素,如果你想要移除所有(包括不相邻的)重复元素,必须先将序列排序,使所有重复元素都相邻。

unique会返回一个迭代器指向新区间的尾端,新区间之内不包含相邻的重复元素。

事实上unique并不改变元素个数,有一些残余数据会留下来,可以用erase函数去除。

#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>

using namespace std;

int main(void)
{   
    vector<int> res = { 2, 3, 4, 5, 2, 3, 4, 5 };
    cout << "移除之前,res数组中元素的个数:" << res.size() << endl;
    sort(res.begin(), res.end());

    vector<int>::iterator ite = unique(res.begin(), res.end());
    cout << "使用unique之后,res数组中元素的个数:" << res.size() << endl;
    res.erase(ite, res.end());
    cout << "使用erase之后,res数组中元素的个数:" << res.size() << endl;
    for(auto i : res)
        cout << i << " ";
    return 0;
}

14行和16行代码可以合并,之间写成:res.erase(unique(res.begin(), res.end()), res.end())。

运行结果:

移除之前,res数组中元素的个数:      8
使用unique之后,res数组中元素的个数:8
使用erase之后,res数组中元素的个数: 4
2 3 4 5

猜你喜欢

转载自blog.csdn.net/chen134225/article/details/81346689