如何在C++中实现argmax功能
导读:在C++中实现argmax功能可以通过以下代码实现: #include <iostream> #include <vector> #include <algorithm> int argmax(cons...
在C++中实现argmax功能可以通过以下代码实现:
#include <
iostream>
#include <
vector>
#include <
algorithm>
int argmax(const std::vector<
int>
&
vec) {
return std::distance(vec.begin(), std::max_element(vec.begin(), vec.end()));
}
int main() {
std::vector<
int>
vec = {
5, 2, 7, 1, 9, 3}
;
int max_index = argmax(vec);
std::cout <
<
"The index of the maximum value is: " <
<
max_index <
<
std::endl;
return 0;
}
在上面的代码中,首先定义了一个argmax函数,该函数接受一个整数类型的vector作为参数,然后使用std::max_element函数找到vector中的最大值的迭代器,并通过std::distance函数计算出最大值的索引位置。最后在main函数中调用argmax函数,找到并输出最大值的索引位置。
声明:本文内容由网友自发贡献,本站不承担相应法律责任。对本内容有异议或投诉,请联系2913721942#qq.com核实处理,我们将尽快回复您,谢谢合作!
若转载请注明出处: 如何在C++中实现argmax功能
本文地址: https://pptw.com/jishu/690570.html