如果元素被保存在vector中,可先对vector里面的元素排序,然后调用unique函数去重,unique(起始迭代器,终止迭代器),返回的是去重以后vector中没有重复元素的下一个位置的迭代器。unique的实现原理大概是判断当前元素是否等于上一个元素,如果等于就将后一个元素向前覆盖掉当前的元素,所以执行完unique()以后返回的迭代器开始到vector.end()的元素都是没有意义的。
如果需要去除重复的元素,可使用下面的代码。
1 #include <algorithm> 2 #include <vector> 3 4 uning namespace std; 5 6 7 vector<int> v; 8 9 sort(v.begin(), v.end()); 10 v.erase(unique(v.begin(), v.end()), v.end());
其中erase的用法是(需要清除的元素的起始迭代器,终止位置的下一个位置的迭代器)。