参考:https://blog.csdn.net/theonegis/article/details/83036074
实现思路
- 使用STL中的
std::min_element
函数求出最小值; - 使用STL中的
std::distance
计算最小值跟迭代器的头部的距离;
#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
网友评论