C 給vector去重的三種方法

2021-09-23 20:31:31 字數 1208 閱讀 3447

第一正種方法是簡單的利用set的特性,這部分**比較簡單,直接上code:

#include #include #include using namespace std;

int main()

; int len = sizeof(myints)/sizeof(int);

vectorvec(myints, myints + len);

sets(vec.begin(), vec.end());

vec.assign(s.begin(), s.end());

for(int x : vec)

cout << x << ",";

return 0;

}

第二種方法是結合sort和unique函式

unique()函式將相鄰且重複的元素放到vector的尾部 然後返回指向第乙個重複元素的迭代器再用erase函式擦除從這個元素到最後元素的所有的元素。

所以可以先進行排序,這樣重複元素就會堆一起了,呼叫unique()函式,再呼叫erase函式刪除重複。**見下:

#include #include #include using namespace std;

int main()

; int len = sizeof(myints)/sizeof(int);

vectorvec(myints, myints + len);

sort(vec.begin(), vec.end());

vec.erase(unique(vec.begin(), vec.end()), vec.end());

for(int x : vec)

cout << x << ",";

return 0;

}

第三種方法是用c++自帶的remove函式:

#include #include #include #include using namespace std;

int main()

vec.push_back(7);

auto ret = std::remove(vec.begin(), vec.end(), 7);

vec.erase(ret, vec.end());

for(auto &i : vec)

return 0;

}

C 給vector去重的三種方法

第一正種方法是簡單的利用set的特性,這部分 比較簡單,直接上code include include include using namespace std int main int len sizeof myints sizeof int vectorvec myints,myints len ...

陣列去重的三種方法

方法一 常規方法 思路 1.構建乙個新的陣列存放結果 2.for迴圈中每次從原陣列中取出乙個元素,用這個元素迴圈與結果陣列對比 3.若結果陣列中沒有該元素,則存到結果陣列中 物件導向,是乙個方法 array.prototype.unique1 function if repeat return re...

陣列去重的三種方法

var arr1 建立臨時陣列 var obj 建立空物件 for var i 0 i arr.length i return arr1 var arr 1,1,1,1,2,3,5,6,6,6 console.log unique arr var arr1 for var i 0 i arr.len...