1.例子:
主要使用函數(shù)unique袱巨、erase、sort
#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>
using namespace std;
int main(void)
{
vector<int> res = {1, 1, 3, 3, 5, 5, 2, 2, 4, 4};
//將數(shù)據(jù)進(jìn)行排序
sort(res.begin(), res.end());
//打印vector的內(nèi)容
for (auto i : res)
cout << i << " ";
cout << endl;
//將重復(fù)的數(shù)據(jù)移到后面
vector<int>::iterator ite = unique(res.begin(), res.end());
cout << "unique res size:" << res.size() << endl;
//刪除重復(fù)的元素
res.erase(ite, res.end());
cout << "erase res size:" << res.size() << endl;
//打印vector的內(nèi)容
for (auto i : res)
cout << i << " ";
return 0;
}
//運(yùn)行結(jié)果
1 1 2 2 3 3 4 4 5 5
unique res size:10
erase res size:5
1 2 3 4 5
2.解釋
? 算法unique能夠移除重復(fù)的元素碳抄。每當(dāng)在[first, last]內(nèi)遇到有重復(fù)的元素群愉老,它便移除該元素群中第一個以后的所有元素。
? 注意:unique只移除相鄰的重復(fù)元素剖效,如果你想要移除所有(包括不相鄰的)重復(fù)元素嫉入,必須先將序列排序,使所有重復(fù)元素都相鄰璧尸。
? unique會返回一個迭代器指向新區(qū)間的尾端咒林,新區(qū)間之內(nèi)不包含相鄰的重復(fù)元素。
事實上unique并不改變元素個數(shù)爷光,有一些殘余數(shù)據(jù)會留下來垫竞,可以用erase函數(shù)去除。