Last active
January 20, 2021 18:40
-
-
Save liuml07/5863759 to your computer and use it in GitHub Desktop.
Remove duplicate elements in a std::vector
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <algorithm> | |
#include <vector> | |
#include <set> | |
template <typename Type> | |
void remove_duplicate(std::vector<Type>& vec) { | |
std::sort(vec.begin(), vec.end()); | |
vec.erase(unique(vec.begin(), vec.end()), vec.end()); | |
} | |
template <typename Type> | |
void remove_duplicate2(std::vector<Type>& vec) { | |
std::set<Type> s(vec.begin(), vec.end()); | |
vec.assign(s.begin(), s.end()); | |
} | |
// See more at: http://stackoverflow.com/questions/1041620/most-efficient-way-to-erase-duplicates-and-sort-a-c-vector |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I believe the arguments should be references for this to work:
change
std::vector<Type> vec
tostd::vector<Type>& vec