Open In App

How to Find Duplicates in a Vector in C++?

Last Updated : 26 Nov, 2024
Comments
Improve
Suggest changes
2 Likes
Like
Report

In this article, we will learn how to find the duplicate elements in a vector in C++.

The easiest way to find the duplicate elements from the vector is by using sort() function to first sort the vector and then check the adjacent elements for duplicates. Let’s take a look at an example:


Output
2 4 5 

Explanation: Vector v is first sorted to group identical elements together. Then by iterating through the vector, we compared each element with the previous one and if they are equal, the element is identified as a duplicate and printed.

There are also some other methods in C++ to find the duplicates in a vector. Some of them are as follows:

Using unordered_map

The unordered_map can be used to find the duplicates in a vector by counting the frequency of each elements.


Output
2 5 4 

Explanation: In this method, after counting the frequency of every elements, we check if the frequency of any element is greater than 1. If it is, that means the element is duplicates.

Using unordered_set

Iterate through the vector and keep the track of the elements visited in an unordered_set. If an element already exists in the unordered_set, it's a duplicate.


Output
4 5 2 

Using Nested Loop

The two loops nested inside one another can be used to find duplicates from the vector. The first loop to iterate over a vector and for each element in the vector, the second loop iterator over the vector to check if this element exists somewhere else or not.


Output
2 5 4 

Next Article
Article Tags :
Practice Tags :

Similar Reads