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.

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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM