Find which numbers appears most in a vector

后端 未结 6 2050
一个人的身影
一个人的身影 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:29

    Try this

    int FindMode(vector value)
    { 
        int index = 0;
        int highest = 0;
        for (unsigned int a = 0; a < value.size(); a++)
        {
            int count = 1;
            int Position = value.at(a);
            for (unsigned int b = a + 1; b < value.size(); b++)
            {
                if (value.at(b) == Position)
                {
                    count++;
                }
            }
            if (count >= index)
            {
                index = count;
                highest = Position;
            }
        }
        return highest;
    }
    

提交回复
热议问题