C++中数组/Vector中去除重复元素
unique函数是一个去重函数,去除相邻中的重复元素(只留一个)。
其中,最关键的是:并不是删除并不是把重复的元素删除,而是全部放倒数组的后面。
因为,unique只是去除(相邻)的重复元素,因此,为了去除重复的元素,应该,首先对数组/Vector进行排序,这样保证重复元素在相邻的位置。
unique函数,返回的是去重后的尾地址。
因此对于一个内容为{2, 2, 5, 5, 6}的vector,执行unique函数以后,vector大小并没有改变,只不过顺序变成了{2, 5, 6, 2, 5},并且函数的返回值为:3。
此时需要删除重复元素,只需要将后面的数据全部删除即可。
排序函数(sort)和去重函数都在<algorithm>头文件中。
1 #include <iostream> 2 #include <algorithm> 3 #include <vector> 4 using namespace std; 5 6 7 int main() { 8 vector<int> v; 9 cout << "Number of vector's element : " << endl; 10 int number; 11 cin >> number; 12 for (int i = 0; i < number; i++) { 13 int temp; 14 cin >> temp; 15 v.push_back(temp); 16 } 17 sort(v.begin(),v.end()); 18 v.erase(unique(v.begin(), v.end()), v.end()); 19 for (int i = 0; i < v.size(); i++) { 20 cout << v[i] << " "; 21 } 22 cout << endl; 23 return 0; 24 }
unique()函数将重复的元素放到vector的尾部 然后返回指向第一个重复元素的迭代器 再用erase函数擦除从这个元素到最后元素的所有的元素