gpt4 book ai didi

c++ - std::max_element 跳过 NAN

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:01:53 27 4
gpt4 key购买 nike

我有一个 std::vector<double>可能包含多个 NAN值。我想找到 vector 中最大的元素。我怎样才能有效地跳过 NAN在比较中?我想避免调用 isnan在每个元素上。有什么想法吗?

// std::max_element([NAN,NAN,NAN,-31,-89]) = NAN 
// because NAN > -31 returns NAN.
// how can I skip all NANs in the comparison?
// test 2 below is my use case.

#include <vector>
#include <iostream>
#include <cmath>

void vector_max(std::vector<double> v, double &max, int &imax){
std::vector<double>::iterator v_iter;
v_iter = std::max_element(v.begin(),v.end());
imax = std::distance(v.begin(), v_iter);
max = *v_iter;
}

int main(){

std::vector<double> v_vec;
std::vector<double>::iterator v_vec_iter;
int imax;
double val;

std::cout << "test 1. " << std::endl;

v_vec.push_back( -33.0 );
v_vec.push_back( -124.0 );
v_vec.push_back( -31.0 );
v_vec.push_back( 18.4 );

vector_max(v_vec,val,imax);
std::cout << "max(v_vec) = " << val << std::endl;
std::cout << "indmax(v_vec) = " << imax << std::endl;

std::cout << "test 2: my case. " << std::endl;

v_vec.clear();
v_vec.push_back( NAN );
v_vec.push_back( NAN );
v_vec.push_back( NAN );
v_vec.push_back( -33.0 );
v_vec.push_back( -124.0 );
v_vec.push_back( -31.0 );
v_vec.push_back( 31.0 );

vector_max(v_vec,val,imax);
std::cout << "max(v_vec) = " << val << std::endl;
std::cout << "indmax(v_vec) = " << imax << std::endl;

};

返回:

test 1. 
max(v_vec) = 18.4
indmax(v_vec) = 3
test 2.
max(v_vec) = nan
indmax(v_vec) = 0

最佳答案

您可以为 max_element 提供自定义比较:

void vector_max(std::vector<double> v, double &max, int &imax){
std::vector<double>::iterator v_iter;
v_iter = std::max_element(v.begin(),v.end(),
[] (auto x, auto y)
{
return x < y ? true : isnan(x);
});
imax = std::distance(v.begin(), v_iter);
max = *v_iter;
}

关于c++ - std::max_element 跳过 NAN,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35889529/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com