在Python中 argmin 和 argmax 这两个函数一般是用来就一列数中的最小值和最大值的索引。C++中我们如何实现呢?
argmin
argmax
std::min_element
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;}
输出结果:
52