Remove duplicates from a vector and keep the order
Description: Remove the duplicates from {4, 7, 4, 1, 7, 9, 1} and keep the order of the first appearance.
Hint:
- Keep an
std::unordered_setof the values you have seen.
Solution
#include <iostream>
#include <unordered_set>
#include <vector>
int main() {
std::vector<int> numbers = {4, 7, 4, 1, 7, 9, 1};
std::unordered_set<int> seen;
std::vector<int> unique;
for (int n : numbers) {
if (seen.insert(n).second) { // insert returns true when it is new
unique.push_back(n);
}
}
for (int n : unique) std::cout << n << ' ';
std::cout << '\n';
}
Output
4 7 1 9
How it works
insertreturns a pair, and the second part isfalsewhen the value was already there.
Read STL Containers.
Learn more about the similar topics:
| Tutorials |
|---|
| No Content Found. |
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |