C++
October 12, 2018

C++中argmin和argmax的实现

C++中argmin和argmax的实现

在Python中argminargmax这两个函数一般是用来就一列数中的最小值和最大值的索引。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