在vector容器中,存入的內容難免會出現重複,那麼如何快速輸出或提前非重複的那些數據呢,即重複的數據只輸出一次,直觀的方法是每次輸出都要通過循環比較是否已經輸出過,這種方法還是比較費時的,可以利用unique函數簡化代碼,例子:
#include "stdafx.h"
#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
using namespace std;
int_tmain(int argc, _TCHAR* argv[])
{
strings;
unsigned int size =0;
vector<string>v;
cout<<"輸入個字符串:"<<endl;
while(size<5)
{
cin>>s;
v.push_back(s);
++size;
}
cout<<"輸入的字符串爲:"<<endl;
copy(v.begin(),v.end(),ostream_iterator<string>(cout,"\n"));
cout<<"排序後的結果爲:"<<endl;
sort(v.begin(),v.end());
copy(v.begin(),v.end(),ostream_iterator<string>(cout,"\n"));
cout<<"不輸出重複的結果:"<<endl;
vector<string>::iteratore = unique(v.begin(),v.end());
for(vector<string>::iterator b=v.begin(); b!=e;b++)
{
cout<<*b<<endl;
}
//再次輸出排序後的結果
cout<<"再次輸出排序後的結果:"<<endl;
copy(v.begin(),v.end(),ostream_iterator<string>(cout,"\n"));
return 0;
}
輸出結果爲: