C++ vector中如何删除重复元素,且保留原顺序
(1)操作vector本身:
#include <vector>
#include <iostream>
using namespace std;
int main()
{
int aa[]={4,2,1,3,3,4,4,1,2};
vector<int> test(aa,aa+9);
vector<int>::iterator it,it1;
for (it=++test.begin(); it != test.end();)
{
it1 = find(test.begin(),it,*it); //若当前位置之前存在重复元素,删除当前元素,erase返回当前元素的下一个元素指针
if(it1 != it)
it=test.erase(it);
else
it++;
}
cout<<"result:"<<endl;
for (it=test.begin();it<test.end();it++)
cout<<*it;
cout<<endl;
system("pause");
}
(2)新建vector保存有序不重复元素:
#include <vector>
#include <iostream>
using namespace std;
int main()
{
int aa[]={4,2,1,3,3,4,4,1,2};
vector<int> test(aa,aa+9);
vector<int> hehe;
vector<int>::iterator it1,it2;
for (it1 = test.begin();it1 < test.end();it1++)
{
it2 = find(test.begin(),it1,*it1);
if (it2 == it1)
hehe.push_back(*it1); //
}
cout<<"result:"<<endl;
for (it1=hehe.begin();it1<hehe.end();it1++)
cout<<*it1;
cout<<endl;
system("pause");
}
若不要求按照数据原来的顺序,可用:
sort(v.begin(),v.end()); //unique只能比较相邻元素是否重复
v.erase(unique(v.begin(), v.end()), v.end()); //unique将重复的元素移到末尾,返回末尾中第一个重复值的地址
1.erase()函数的用法:
erase()函数用于在顺序型容器中删除容器的一个元素,有两种函数原型,c.erase(p),c.erase(b,e);第一个删除迭代器p所指向的元素,第二个删除迭代器b,e所标记的范围内的元素,c为容器对象,返回值都是一个迭代器,该迭代器指向被删除元素后面的元素(这个是重点)