c++ - C++ 中是否有任何预定义函数可以从给定数组中查找最小和最大元素?
问题描述
我有一个数组
double weights[]={203.21, 17.24, 125.32, 96.167}
如果有的话,我希望通过使用函数来计算最小和最大元素?请帮忙
解决方案
是的,有:std::minmax_element。还有 用于查找最大值的std::max_element和用于查找最小值的 std::min_element。
应用于您的代码:
#include <algorithm>
#include <iterator>
int main() {
double weights[]={203.21, 17.24, 125.32, 96.167};
auto minMaxIterators = std::minmax_element(std::begin(weights), std::end(weights));
// minMaxIterators is a pair of iterators. To find the actual doubles
// themselves, we have to separate out the pair and then dereference.
double minWeight = *(minMaxIterators.first);
double maxWeight = *(minMaxIterators.second);
// Alternately, using structured bindings to extract elements from the pair
auto [minIt, maxIt] = std::minmax_element(std::begin(weights), std::end(weights));
minWeight = *minIt;
maxWeight = *maxIt;
// Alternately, using min_element and max_element separately
minWeight = *(std::min_element(std::begin(weights), std::end(weights)));
maxWeight = *(std::max_element(std::begin(weights), std::end(weights)));
}
推荐阅读
- python-3.x - For循环遍历元组A并增加元组Ai给定大小N到可迭代的Ni
- python - 由于 SSL 证书错误,Windows 10 无法安装 Pip
- django-rest-framework - 使用 Django REST 框架和令牌身份验证的服务器端会话
- c++ - 具有非常量值的 c++ 数组索引
- azure - 主机名可用但未显示在 Azure 门户中以供购买
- amazon-web-services - 使用 SNS 发送推送通知 - Expo App
- python - 如何以管理员权限打开外部程序?
- javascript - TypeError:调用类方法时不是函数
- javascript - 工作箱 precacheAndRoute 不处理 window.fetch 或 XMLHttpRequest
- python-3.x - 删除附加到数据框中值的垃圾('[',']','等)