C++ : How to Find Duplicates in a Vector

In the previous article, we have discussed about boost::any Usage in CPP. Let us learn how to find factorial in C++ Program.

Vector:

Vectors, like dynamic arrays, can resize themselves when an element is added or removed, and the container manages their storage. Since vector elements are stored in contiguous storage, iterators can access and traverse them. Vectors have data inserted at the end. Since the array can need to be expanded at times, inserting at the end takes longer. The final variable is not resized, and removing it requires the same amount of time. In terms of time, inserting and erasing at the beginning or in the middle is linear.

Given a Vector , the task is to print the duplicate elements in the vector and their count

Example:

Input:

Vector = {"Hello","this","is","Hello","BTechGeeks","is" ,"this","this","platform"}

Output:

Printing the duplicate elements and their frequency : 
Hello ::::: 2
is ::::: 2
this ::::: 3

Find Duplicates in a Vector

Algorithm using maps in C++

  • To store the frequency count of each string in a vector, create a map of type <string, int>.
  • Iterate over all of the elements in the vector and attempt to insert them as a key in the map with a value of 1.
  • If the string already exists in the map, increase the value by 1.

Below is the implementation:

#include <bits/stdc++.h>
using namespace std;
int main()
{
    // Creating a string vector and initializing with some
    // strings
    vector<string> stringvector
        = { "Hello", "this",       "is",
            "Hello", "BTechGeeks", "is",
            "this",  "this",       "platform" };
    // creating a new map with key as string and value as
    // integer

    map<string, int> freqMap;
    // Iterate through the vector, tracking the frequency of
    // each element in the map.
    for (auto& element : stringvector) {
        auto res
            = freqMap.insert(pair<string, int>(element, 1));
        if (res.second == false)
            res.first->second++;
    }
    cout << "Printing the duplicate elements and their "
            "frequency : "
         << endl;
    // Traverse the map
    for (auto& element : freqMap) {
        // If the frequency count is greater than 1, the
        // variable is duplicated.
        if (element.second > 1) {
            cout << element.first
                 << " ::::: " << element.second << endl;
        }
    }

    return 0;
}

Output:

Printing the duplicate elements and their frequency : 
Hello ::::: 2
is ::::: 2
this ::::: 3

Related Programs: