algorithm之unique
#include<iostream>
#include<algorithm>
usingnamespace std;
/**< unique函数的算法思想 */
vector<int>::iterator uniqueElements(vector<int>::iterator begPos,vector<int>::iterator endPos)
{
auto currPos = begPos +1;
while(currPos != endPos)
{
if(*begPos !=*currPos)
*(++begPos)=*(currPos++);
else
++currPos;
}
return begPos+1;
}
int main()
{
vector<int> intVector;
for(int i =0; i <20;++i)
{
intVector.push_back(rand()%10);
}
for(auto val : intVector)
{
cout << val <<" ";
}
cout << endl;
sort(intVector.begin(), intVector.end());
for(auto val : intVector)
{
cout << val <<" ";
}
cout << endl;
auto end_unique = unique(intVector.begin(), intVector.end());
/**< 可以查看算法,unique并不是简单的将重复的元素放置到最后面去 */
for(vector<int>::iterator it = intVector.begin(); it != intVector.end();++it)
{
if(it == end_unique)
cout <<"##";
cout <<*it <<" ";
}
cout << endl;
intVector.erase(end_unique,intVector.end());
for(auto val:intVector )
cout << val <<" ";
cout << endl;
return0;
}