Skip to content

Instantly share code, notes, and snippets.

@liuml07
Last active January 20, 2021 18:40
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save liuml07/5863759 to your computer and use it in GitHub Desktop.
Save liuml07/5863759 to your computer and use it in GitHub Desktop.
Remove duplicate elements in a std::vector
#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
@qvandenberg
Copy link

I believe the arguments should be references for this to work:
change std::vector<Type> vec to std::vector<Type>& vec

@liuml07
Copy link
Author

liuml07 commented Jan 20, 2021

Thank you @qvandenberg! Updated.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment