Search code examples
c++vectormaxminstd-pair

Finding the minimum and maximum values in a std::vector of std::pair


I'm trying to find out the minimum and maximum value in a vector of pair<int, std::string>.

My Code:

#include <iostream>
#include <vector>
#include <string>

int main()
{
    std::vector<std::pair<int, std::string>> pairs;
    pairs = {{6,"a"}, {4,"b"}, {5,"c"}, {8,"d"}, {7,"e"}};

    int min = 0, max = 0;

    // How can I find out the minimum and maximum?

    std::cout << "Minimum Number: " << min << '\n';
    std::cout << "Maximum Number: " << max << '\n';
}

The result I want:

Minimum Value: 4
Maximum Value: 8
Program ended with exit code: 0

How can I get the result I want?


Here's my solution so far.

std::sort(pairs.begin(), pairs.end());
min = pairs[0].first;
max = pairs[pairs.size()-1].first;

Although it works, I would like to learn a simpler and faster solution than this.


Solution

  • You might use std::minmax_element:

     const auto p = std::minmax_element(pairs.begin(), pairs.end());
     auto min = p.first->first;
     auto max = p.second->first;