简体   繁体   中英

How to get the most frequent element of a list?

Let's say I have a list:

std::list<std::string> list ("the", "the", "friend", "hello", "the");

In this case, the most common element in the list is "the" . Is there a way to get this element in C++??

Thanks!

A general algorithm to solve your problem is to build a dictionary of word frequencies. Here is a pseudo code algorithm, that does exactly that:

let L be the input sequence of strings (can be a list, doesn't matter)
let F be an empty dictionary that maps string to a number
for each string S in L
    if not F contains S then
        F[S] = 0
    F[S] += 1

Once the dictionary is constructed, all you need to do is to find the mapping with the highest value, and return the key.

The C++ standard library provides associative containers (aka dictionaries, aka maps ), and an algorithm for searching for the greatest element within a container.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM