c++ STL unique()+remove()函数去除容器内重复元素
2009-09-15 23:03
#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>
/* 删除容器内重复元素,分三步处理
* 1、先排序容器元素
* 2、取得重复元素首部迭代器
* 3、删除重复元素
*/
using namespace std;
int main()
{
int a[]={1,2,3,1,2,4,4,5};
const int len = sizeof(a)/sizeof(int);
vector<int> va(len);// 定义一个与数组等长的容器
copy(a, a + len, va.begin());
ostream_iterator<int, char> oi(cout," ");//定义一个输出流迭代器
copy(va.begin(), va.end(), oi);
cout << " 容器内元素顺序输出结果" << endl;
// sort(两个参数)默认升序排列元素,如果不是基本类型,请重载操作符opearte<.
// sort (三个参数) sort(va.begin(),va.end(),handle_v);
// 自己写函数实现处理两个元素参数 bool handle_v(const int & a,cont int & b){};
sort(va.begin(), va.end());
vector<int>::iterator it = unique(va.begin(),va.end());
va.erase(it, va.end());
copy(va.begin(), va.end(), oi);
cout << " 删除重复元素后顺序输出结果" << endl;
return 0;
}
#include <vector>
#include <algorithm>
#include <iterator>
/* 删除容器内重复元素,分三步处理
* 1、先排序容器元素
* 2、取得重复元素首部迭代器
* 3、删除重复元素
*/
using namespace std;
int main()
{
int a[]={1,2,3,1,2,4,4,5};
const int len = sizeof(a)/sizeof(int);
vector<int> va(len);// 定义一个与数组等长的容器
copy(a, a + len, va.begin());
ostream_iterator<int, char> oi(cout," ");//定义一个输出流迭代器
copy(va.begin(), va.end(), oi);
cout << " 容器内元素顺序输出结果" << endl;
// sort(两个参数)默认升序排列元素,如果不是基本类型,请重载操作符opearte<.
// sort (三个参数) sort(va.begin(),va.end(),handle_v);
// 自己写函数实现处理两个元素参数 bool handle_v(const int & a,cont int & b){};
sort(va.begin(), va.end());
vector<int>::iterator it = unique(va.begin(),va.end());
va.erase(it, va.end());
copy(va.begin(), va.end(), oi);
cout << " 删除重复元素后顺序输出结果" << endl;
return 0;
}