STL Vectors — Print two highest values in list in descending order

--

Sometimes in our work we need to get several highest values in list in descending order.

Here is a very simple algorithm to solve this problem for three values

Let’s define a list

vector<int> numbers = {5, 13, 7, 24};

Then sort the list in descending order. First way to do that is

sort(nums.rbegin(), nums.rend());

Second way is

sort(nums.begin(), nums.end(), greater<int>());

You can read about greater here.

Now simply print first two values which should be highest ones

cout << nums[0] << ", " << nums[1] << endl;

--

--

No responses yet