cpp 实现 argmax, argmin 求数组的最大值,最小

2019-05-06  本文已影响0人  谢小帅

参考:https://blog.csdn.net/theonegis/article/details/83036074

实现思路

#include <iostream>
#include <algorithm>
#include <vector>

using namespace std;

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

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


int main() {
    vector<double> v{1, 2, 33, 41, 5.0, 100, 27, 0, 40, 50};
    cout << "vector: " << argmax(v.begin(), v.end()) << ", " << argmin(v.begin(), v.end()) << endl;

    // 也可用于数组
    int a[] = {1, 2, 33, 41, 5, 100, 27, 0, 40, 50}; // len=10
    cout << "array: " << argmax(a, a + 10) << ", " << argmin(a, a + 10) << endl;
}
vector: 5, 7
array: 5, 7
上一篇下一篇

猜你喜欢

热点阅读