How to Find the Mode of Vector in C++?

In C++, a vector is a dynamic array that resizes itself when needed. It also allows random access to its elements. In this article, we will learn how to find the mode of a vector in C++. The mode of a vector is the element that highest number of occurrences in the vector.

Example:

Input:
myVector = { 1, 2, 3, 4, 5, 2, 3, 2, 2, 4, 2 }

Output:
Mode : 2

Finding Mode of Vector in C++

We can find the mode of a vector in C++ using a std::map container to count the frequency of each element in the vector, and then find the element with the maximum frequency.

C++ Program for Finding Mode of Vector in C++

C++




// C++ Program to find mode of all Elements in a vector
#include <iostream>
#include <unordered_map>
#include <vector>
using namespace std;
  
// Function to find the mode of a vector
int findMode(const vector<int>& nums)
{
    // Create an unordered map to store frequency of each
    // element
    unordered_map<int, int> frequency;
  
    // Iterate through the vector and update frequency of
    // each element
    for (int num : nums) {
        frequency[num]++;
    }
  
    // Initialize variables to keep track of mode and its
    // frequency
    int mode = 0;
    int maxFrequency = 0;
  
    // Iterate through the unordered map and find the
    // element with maximum frequency
    for (const auto& pair : frequency) {
        if (pair.second > maxFrequency) {
            maxFrequency = pair.second;
            mode = pair.first;
        }
    }
  
    // Return the mode
    return mode;
}
  
// Driver Code
int main()
{
    // Create a vector of numbers
    vector<int> numbers
        = { 1, 2, 3, 4, 5, 2, 3, 2, 2, 4, 2 };
  
    // Find the mode of the vector
    int mode = findMode(numbers);
  
    // Print the mode
    cout << "Mode: " << mode << endl;
  
    return 0;
}


Output

Mode: 2

Time complexity: O(N)
Space complexity: O(N)



Contact Us