Home > Software design >  most common string in a vector using c [closed]
most common string in a vector using c [closed]

Time:10-01

For example I have vector {'a','b','b','c'} and I want to get the most letters which is b but this code the output is 98;

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>

int getMostFrequentElement(std::vector<char> &arr)
{
    if (arr.empty())
        return -1;

    std::sort(arr.begin(), arr.end());

    auto last_int = arr.front();
    auto most_freq_int = arr.front();
    int max_freq = 0, current_freq = 0;

    for (const auto &i : arr) {
        if (i == last_int)
              current_freq;
        else {
            if (current_freq > max_freq) {
                max_freq = current_freq;
                most_freq_int = last_int;
            }

            last_int = i;
            current_freq = 1;
        }
    }

    if (current_freq > max_freq) {
        max_freq = current_freq;
        most_freq_int = last_int;
    }

    return most_freq_int;
}

int main(){
    std::vector<char> arr = {'a','b','b','c'};

    int ret = getMostFrequentElement(arr);
  
    std::cout << "Most frequent element = " << ret;

    
}

May I know why my output becomes 98 instead b?

input vector arr{'a','b','b','c' expected output is b

but my output is 98

CodePudding user response:

98 is the ASCII number associated with b you will need to change your output from an int to a char:

char ret = getMostFrequentElement(arr);

should work

CodePudding user response:

ret variable should be a char

char ret = getMostFrequentElement(arr)

  • Related