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;
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?