c++ - 在 std::pair 的 std::vector 中查找最小值和最大值
问题描述
我试图找出向量中的最小值和最大值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 can I find out the minimum and maximum?
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;
推荐阅读
- c# - Socket 连接的 Xunit 测试功能(ModbusTCP/IP)
- unity3d - Unity:无法从 HDR 显示器获取信息。此项目的播放器设置中未启用 HDR
- java - 滑动后如何在 RecyclerView 中向后滑动项目
- reactjs - Material UI TreeView 递归渲染是如何工作的?
- django - 如何在 Django 中使用 Ajax 更改图像 url
- cryptocurrency - 请解释同一个钱包中同一个硬币的同时进出交换
- javascript - React Component 不会以父组件的给定状态呈现
- django - 我提出了两个验证错误,但如果其中任何一个被触发,它总是给我相同的验证错误输出
- kotlin - 如何在 tornadofx imageview 中显示新图像?
- python - (imutils)PackagesNotFoundError:当前频道不提供以下软件包: