How do I remove duplicates with std::unordered_set?

To remove duplicates from a collection using C++, you can utilize the std::unordered_set container. This container does not allow duplicate elements and is ideal for achieving this task efficiently.

Below is an example demonstrating how to remove duplicates from a vector using std::unordered_set.

#include #include #include void removeDuplicates(std::vector& vec) { std::unordered_set seen; auto it = vec.begin(); while(it != vec.end()) { if(seen.find(*it) != seen.end()) { it = vec.erase(it); // Remove duplicate } else { seen.insert(*it); ++it; // Move to next element } } } int main() { std::vector vec = {1, 2, 3, 2, 4, 1, 5}; removeDuplicates(vec); for(int num : vec) { std::cout << num << " "; // Output: 1 2 3 4 5 } return 0; }

Remove Duplicates std::unordered_set C++ Programming STL C++ Example