0
点赞
收藏
分享

微信扫一扫

C++中argmin和argmax的实现

Ichjns 2022-08-01 阅读 49


C++中argmin和argmax的实现

在Python中​​argmin​​​和​​argmax​​这两个函数一般是用来就一列数中的最小值和最大值的索引。C++中我们如何实现呢?

实现思路

  1. 使用STL中的​​std::min_element​​函数求出最小值;
  2. 使用STL中的​​std::distance​​计算最小值跟迭代器的头部的距离;

实现代码

#include <algorithm>

template<class ForwardIterator>
inline size_t argmin(ForwardIterator first, ForwardIterator last)
{
return std::distance(first, std::min_element(first, last));
}

template<class ForwardIterator>
inline size_t argmax(ForwardIterator first, ForwardIterator last)
{
return std::distance(first, std::max_element(first, last));
}

测试代码

int main() {
array<int, 7> numbers{2, 4, 8, 0, 6, -1, 3};
size_t minIndex = argmin(numbers.begin(), numbers.end());
cout << minIndex << '\n';
vector<float> prices = {12.5, 8.9, 100, 24.5, 30.0};
size_t maxIndex = argmax(prices.begin(), prices.end());
cout << maxIndex << '\n';
return 0;
}

输出结果:

5
2


举报

相关推荐

0 条评论