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