1. 程式人生 > >C++中的unique函數

C++中的unique函數

algo scanf 利用 重復 除了 一個 image 功能 就會

轉自:https://blog.csdn.net/tomorrowtodie/article/details/51907471

unique()是C++標準庫函數裏面的函數,其功能是去除相鄰的重復元素(只保留一個),所以使用前需要對數組進行排序

n = unique(a,a+n) - a;

上面的一個使用中已經給出該函數的一個使用方法,對於長度為n數組a,unique(a,a+n) - a返回的是去重後的數組長度

那它是怎麽實現去重的呢?刪除?

不是,它並沒有將重復的元素刪除,而是把重復的元素放到數組的最後面藏起來了

當把原長度的數組整個輸出來就會發現:

技術分享圖片

其中 1 2 8 9 10就是去重後的數組,我這裏把後面“藏起來”的數也輸出了,方便理解

#include<cstdio>
#include<algorithm>
#include<vector>
using namespace std;
const int N = 1000;
int a[N + 5];
int main()
{
    int n;
    while (cin >> n)
    {
        for (int i = 0;i < n;++i) scanf("%d",&a[i]);
        sort (a, a + n);
        vector<int>v (a, a + n);
        vector
<int>::iterator it = unique (v.begin(), v.end() ); v.erase (it, v.end() );//這裏就是把後面藏起來的重復元素刪除了 for ( it = v.begin() ; it != v.end() ; it++ ) { printf ("%d ", *it); } puts(""); } return 0; }

技術分享圖片

這個就是利用vector把後面藏著的元素刪除了

C++中的unique函數