c++11 实现numpy argmax argmin
#include <algorithm> #include <vector> #include <iostream> #include <array> using namespace std; 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.5f, 8.9f, 100.0f, 24.5f, 30.0f }; size_t maxIndex = argmax(prices.begin(), prices.end()); cout << maxIndex << '\n'; return 0; }
运行结果:
5 2
即返回的索引值分别为5,2.