How to counting the most common element in a vector?

Whit STLs library vector????

Example
Input
1,1,2,1,1,3,3,4,5

output
4

HELP...
Last edited on
A simple solution would be to use std::count() on every element of the vector.
Note, the C++98 code below was not tested.

1
2
3
4
std::size_t c=0; // Count of most common element

for (std::vector<int>::const_iterator ci = vi.begin(); ci != vi.end(); ++ci)
    c = std::max(std::count(vi.begin(), vi.end(), *ci), c);


http://www.cplusplus.com/reference/algorithm/count/
http://www.cplusplus.com/reference/algorithm/max/
Topic archived. No new replies allowed.