STL中的sort和unique函数

``````#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
int main()
{
int array[8]={1,5,4,5,3,100,2,100};
vector<int> ivec(array,array+8);
cout<<"元素数据"<<endl;
for(vector<int>::iterator iter=ivec.begin();iter!=ivec.end();++iter)
cout<<*iter<<'\t';
cout<<endl;
sort(ivec.begin(),ivec.end());
cout<<"经sort()排序后"<<endl;
for(vector<int>::iterator iter=ivec.begin();iter!=ivec.end();++iter)
cout<<*iter<<'\t';
cout<<endl;
cout<<"经unique()排序后"<<endl;
vector<int>::iterator it=unique(ivec.begin(),ivec.end());
for(vector<int>::iterator iter=ivec.begin();iter!=ivec.end();++iter)
cout<<*iter<<'\t';
cout<<endl;
cout<<"输出重复数字"<<endl;
for(vector<int>::iterator iter=it;iter!=ivec.end();++iter)
cout<<*iter<<'\t';
cout<<endl;
return 0;
}

``````

1个回答

``````    int array[8] = { 1, 5, 4, 5, 3, 100, 2, 100 };
vector<int> ivec(array, array + 8);
cout << "元素数据" << endl;
for (vector<int>::iterator iter = ivec.begin(); iter != ivec.end(); ++iter)
cout << *iter << '\t';
cout << endl;
sort(ivec.begin(), ivec.end());
cout << "经sort()排序后" << endl;
for (vector<int>::iterator iter = ivec.begin(); iter != ivec.end(); ++iter)
cout << *iter << '\t';
cout << endl;
cout << "经unique()排序后" << endl;
vector<int>::iterator it = unique(ivec.begin(), ivec.end());
ivec.erase(it, ivec.end());

for (vector<int>::iterator iter = ivec.begin(); iter != ivec.end(); ++iter)
cout << *iter << '\t';
cout << endl;
//cout << "输出重复数字" << endl;
//for (vector<int>::iterator iter = it; iter != ivec.end(); ++iter)
//  cout << *iter << '\t';
//cout << endl;
return 0;
``````