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_set of 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

  • insert returns a pair, and the second part is false when the value was already there.

Read STL Containers.


Learn more about the similar topics:
Tutorials
C++ Templates and Generic Programming
C++ STL Containers: map, set, unordered_map, queue and stack
C++ Algorithms and Iterators
Exercises & Assignments
Write a generic maximum template
Count the frequency of words with a map
Remove duplicates from a vector and keep the order
Interview Questions & Answers
What is the STL in C++?
What is the difference between std::map and std::unordered_map?
What is the difference between push_back and emplace_back in C++?
What is iterator invalidation in C++?
What is the difference between templates and macros in C++?