c++如何對vector進行去重

第一種,利用set容器的特性進行去重:

#include <iostream>
#include <vector>
#include <set>
using namespace std;
int main() {
    vector<int>test={1,2,3,3,3,4,2,3,5,2,63,56,34,24};
    set<int>s(test.begin(), test.end());//set會自動進行排序。
    test.assign(s.begin(), s.end());//assign() 函數將區間[start, end)的元素賦到當前vector,
    //或者賦num個值爲val的元素到vector中.這個函數將會清除掉vector以前的內容.
    //可以用於不同容器之間的賦值。
    for(int x : test)
        cout << x <<" ";
    return 0;
}

處理之後的結果:

第二種方法:利用unique函數進行處理。

                unique函數是STL庫中比較常用函數,顧名思義,它的作用就是對相鄰元素進行去重,但是它的去重並不是直接刪除,而是將重複元素的位置(除了第一個重複元素外)讓給後面的元素。  所以一般都要先進行排序,函數的原型是

 iterator unique(iterator it_1,iterator it_2);

很明顯它返回的是一個迭代器,這個迭代器的指向是去重後容器中不重複序列的最後一個元素的下一個元素,比如:

 

a={1,2,3,4,5,2,2,3},假設a是作用過的元素,返回的迭代器指向第二個2。所以直接刪除掉2 2 3這三個數就相當於去重結束。

#include <iostream>
#include <vector>
#include <set>
using namespace std;
int main() {
    vector<int>test={1,2,3,3,3,4,2,3,5,2,63,56,34,24};
    sort(test.begin(),test.end());
    test.erase(unique(test.begin(),test.end()),test.end());
    for(int x:test)
        cout<<x<<" ";
    return 0;
}

處理之後的結果:

但是不知道是不是leetcode的原因,一個耗時4ms,一個耗時<0ms.

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章