STL笔记(こ)--删除数组中重复元素

使用STL中的Unique函数:

 1 #include<bits/stdc++.h>
 2 using namespace std;
 3 void fun(int &n) //配套for_each输出vector容器
 4 {
 5     cout<<n<<" ";
 6 }
 7 int main()
 8 {
 9     vector<int>    a;
10     a.push_back(1);a.push_back(5);a.push_back(1);
11     a.push_back(5);a.push_back(0);a.push_back(5);
12     for_each(a.begin(),a.end(),fun);
13     cout<<endl;
14     
15     sort(a.begin(),a.end());
16     vector<int>::iterator it;
17     it = unique(a.begin(), a.end());
18     // 去重原理:找到重复的数据后移动到最后,然后返回第一个重复的元素的地址
19     a.erase(it, a.end());
20      // 删掉重复的元素
21 
22     for_each(a.begin(),a.end(),fun);
23     cout<<endl;
24     return 0;
25 }

猜你喜欢

转载自www.cnblogs.com/DSYR/p/9245469.html