Is it possible to find the second maximum number from an array of integers by traversing the array only once?
As an example, I have a array of five integers from whi
Here you are:
std::pair GetTwoBiggestNumbers(const std::vector& array)
{
std::pair biggest;
biggest.first = std::max(array[0], array[1]); // Biggest of the first two.
biggest.second = std::min(array[0], array[1]); // Smallest of the first two.
// Continue with the third.
for(std::vector::const_iterator it = array.begin() + 2;
it != array.end();
++it)
{
if(*it > biggest.first)
{
biggest.second = biggest.first;
biggest.first = *it;
}
else if(*it > biggest.second)
{
biggest.second = *it;
}
}
return biggest;
}