Find which numbers appears most in a vector

后端 未结 6 2055
一个人的身影
一个人的身影 2021-01-19 02:57

I have some numbers stored in a vector . I want to find which number appears most in the vector.

Is there any easy/fast algorithm (STL or whatever) that does this ?<

6条回答
  •  终归单人心
    2021-01-19 03:23

    Here is an O(n) generic solution for finding the most common element in an iterator range. You use it simply by doing:

    int commonest = most_common(my_vector.begin(), my_vector.end());
    

    The value type is extracted from the iterator using iterator_traits<>.

    template::value_type>
    T most_common(InputIt begin, InputIt end)
    {
        std::map counts;
        for (InputIt it = begin; it != end; ++it) {
            if (counts.find(*it) != counts.end()) {
                ++counts[*it];
            }
            else {
                counts[*it] = 1;
            }
        }
        return std::max_element(counts.begin(), counts.end(),
                [] (const std::pair& pair1, const std::pair& pair2) {
                return pair1.second < pair2.second;})->first;
    }
    

提交回复
热议问题