unique from STL

去重函数,去掉相邻元素中一样的

其实是把后面不重复的移动到前面来!!!!!!!!

需要配合sort使用,

但是要注意它并没有把元素删除,而是把那个元素放到了最后

#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<cmath>
#include<iostream>
#include<algorithm>
#include<string>
#include<vector>
#include<queue>
#include<map>
#include<set>
#include <stack>
using namespace std;

int main() {

    int n;
    int a[10000];
    while (cin >> n) {
        for (int i = 0; i < n; ++i) {
            scanf("%d", &a[i]);
        }
        sort(a, a + n);
        int k = unique(a, a + n) - a;
        for (int i = 0; i < n; ++i) {
            printf("%d ", a[i]);
        }
        puts("");
    }
}

看看输出:

 

 但是如果你想完完全全把它去掉,那就配合使用一下vector

 1 #include<cstdio>
 2 #include<algorithm>
 3 #include<vector>
 4 #include <iostream>
 5 using namespace std;
 6 const int N = 1000;
 7 int a[N + 5];
 8 int main()
 9 {
10     int n;
11     while (cin >> n)
12     {
13         for (int i = 0;i < n;++i) scanf("%d",&a[i]);
14         sort (a, a + n);
15         vector<int>v (a, a + n);
16 
17         vector<int>::iterator it = unique (v.begin(), v.end() );//注意返回值
18         cout<<*it<<endl;
19         v.erase (it, v.end() );//这里就是把后面藏起来的重复元素删除了
20         for ( it = v.begin() ; it != v.end() ; it++ )
21         {
22             printf ("%d ", *it);
23         }
24         puts("");
25     }
26     return 0;
27 }

 

posted @ 2020-11-07 12:10  安之若醇  阅读(143)  评论(0编辑  收藏  举报
Live2D服务支持