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 ?<
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;
}