This post will discuss how to find all duplicates present in a vector in C++.

1. Using std::set_difference

To find duplicates present in a vector, we can find the set difference between the original elements and the distinct elements. The following code example demonstrates this using the standard algorithm std::set_difference. It constructs a sorted range with the set difference of the specified sorted ranges.

Download  Run Code

Output:

2 6

2. Using Set

Another option is to traverse the vector and keep a record of all the seen elements in a Set. If any element is already present in the Set, then it must be a duplicate. This logic would translate to the following C++ code:

Download  Run Code

Output:

6 2

3. Using frequency map

Alternatively, we can create a frequency map and filter all keys having their value greater than 1. This can be implemented as follows in C++.

Download  Run Code

Output:

2 6

That’s all about finding all duplicates present in a vector in C++.