删除重复元素 需要用两个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
对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 对应 >