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:
- python how to find all indexes of an item in a list
- how to copy all values from a map to a vector in cpp
- how to find and drop duplicate columns in a dataframe python pandas
- how to fill a vector with random numbers in cpp
- how to create and initialize a list of lists in python
- how to append text or lines to a file in python
- python how to check if a key exists in dictionary