我试图找出pair<int, std::string>
矢量中的最小值/最大值
我的代码:
#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 to find out min/max?
std::cout << "Minimum Number : " << min << '\n';
std::cout << "Maximum Number : " << max << '\n';
}
我想要的结果:
Minimum Value : 4
Maximum Value : 8
Program ended with exit code: 0
我怎样才能得到我想要的结果?
编辑:
这是我迄今为止的解决方案。
std::sort(pairs.begin(), pairs.end());
min = pairs[0].first;
max = pairs[pairs.size()-1].first;
虽然它有效,但我想学习一种更简单,更快速的解决方案。
你可以使用std::minmax_element
:
const auto p = std::minmax_element(pairs.begin(), pairs.end());
auto min = p.first->first;
auto max = p.second->first;