[C++]vector去除重复元素

时间:2023-11-10 08:12:50
#include <iostream>
#include <vector>
#include <algorithm>
#include <set> using namespace std; /**
* vector去除重复元素
* @tparam T
* @param result
* @return
*/
template<typename T>
vector<T> vector_distinct(vector<T> result) {
sort(result.begin(), result.end());
auto ite = unique(result.begin(), result.end());
//删除重复的元素
result.erase(ite, result.end());
return result;
} /**
* 利用set为vector数组去重
* @tparam T
* @param vec
* @return
*/
template<typename T>
vector<T> vectorToset_distinct(vector<T> vec) { set<T> st(vec.begin(), vec.end());
vec.assign(st.begin(), st.end());
return vec;
} int main() {
vector<string> v_str1 = {"a", "b", "c", "d", "e", "b"};
vector<string> v_res = vector_distinct(v_str1);
vector<string> vs_res = vectorToset_distinct(v_str1);
cout << "v_str1=";
for (auto v:v_str1) {
cout << v << ",";
}
cout << endl;
cout << "v_res=";
for (auto v:v_res) {
cout << v << ",";
}
cout << endl;
cout << "vs_res=";
for (auto v:vs_res) {
cout << v << ",";
}
cout << endl;
}

[C++]vector去除重复元素