zoukankan      html  css  js  c++  java
  • 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 }
  • 相关阅读:
    移动端WEB开发真机测试
    前端自学路线之js篇
    学习提高你CSS技术的法则
    day-5元组专区
    day5-列表专区
    day4-字符串专区
    day2-day3基本数据类型专区
    day1-习题
    day1-python条件语句和基本数据类型
    day1-python初识以及变量
  • 原文地址:https://www.cnblogs.com/zhmlzhml/p/13940574.html
Copyright © 2011-2022 走看看