Find which numbers appears most in a vector

后端 未结 6 2056
一个人的身影
一个人的身影 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-19 03:29

    You can use the following code:

    vector  v;
        // add some elements
        v.push_back(1);
        v.push_back(2);
        v.push_back(3);
        v.push_back(1);
    
        int maxCount = 0, mostElement = *(v.begin());
        int sz = v.size(); // to avoid calculating the size every time
        for(int i=0; i < sz; i++)
        {
            int c = count(v.begin(), v.end(), v.at(i));
            if(c > maxCount)
            {   maxCount = c;
                mostElement = v.at(i);
            }
        }
        cout << "the number appeared the most is " << mostElement <<"\n";
        cout << "it appered " <

    note: you can use the following for loop to avoid any iterator overflow if the size of the vector can't be held by an integer:

        for(auto it= v.begin(); it != v.end(); it++)
        {
            int c = count(v.begin(), v.end(), *it);
            if(c > maxCount)
            {   maxCount = c;
                mostElement = *it;
            }
        }
    

提交回复
热议问题