In this article we will discuss how to find duplicate elements in vector and their repetition count.

Suppose we have a vector of strings i.e.

Let’s find duplicate elements from this list and their duplication count. For example in above vector duplicate strings and their duplication count is as follows,

Let’s see how to do that,

Finding duplicates in a vector

Steps are :

  • Create a map of <string , int> type to store the frequency count of each string in vector.
  • Iterate over all the elements in vector try to insert it in map as key with value as 1.
    • If string already exists in map then increment its value by 1.

  • Now iterate over the map and print items whose value is greater than 1 i.e.

It will print duplicate elements in vector and their duplication count i.e.

Generic function to find duplicates in vector :

Create a Generic function to get the duplicate elements and their duplication count i.e.

Let’s use this generic function to find duplicate elements in vector i.e.

Now Iterate over this map to print the duplicate elements with count i.e.

Output:

Complete example is as follows,

Output:

To compile the example use following command,

g++ –std=c++11 example.cpp

Click Here to Subscribe for more Articles / Tutorials like this.