find mode c++ stl code example

Example: how to find the mode of a vector c++

//copied from GeeksForGeeks
#include <bits/stdc++.h> 
using namespace std; 
  
// Function that sort input array a[] and 
// calculate mode and median using counting 
// sort. 
void printMode(int a[], int n) 
{  
    int b[n]; 
    int max = *max_element(a, a + n); 
    int t = max + 1; 
    int count[t]; 
    for (int i = 0; i < t; i++) 
        count[i] = 0; 
    for (int i = 0; i < n; i++) 
        count[a[i]]++; 
    int mode = 0; 
    int k = count[0]; 
    for (int i = 1; i < t; i++) { 
        if (count[i] > k) { 
            k = count[i]; 
            mode = i; 
        } 
    } 
  
    cout << "mode = " << mode; 
} 
//Just Include this in your template and call the function printMode 
//to print the mode

Tags:

Cpp Example