Finding the maximum element value AND its position using CUDA Thrust

后端 未结 2 370
庸人自扰
庸人自扰 2020-12-28 08:38

How do I get not only the value but also the position of the maximum (minimum) element (res.val and res.pos)?

thrust::host_vector&l         


        
2条回答
  •  攒了一身酷
    2020-12-28 08:58

    Don't use thrust::reduce. Use thrust::max_element (thrust::min_element) in thrust/extrema.h:

    thrust::host_vector h_vec(100);
    thrust::generate(h_vec.begin(), h_vec.end(), rand);
    thrust::device_vector d_vec = h_vec;
    
    thrust::device_vector::iterator iter =
      thrust::max_element(d_vec.begin(), d_vec.end());
    
    unsigned int position = iter - d_vec.begin();
    float max_val = *iter;
    
    std::cout << "The maximum value is " << max_val << " at position " << position << std::endl;
    

    Be careful when passing an empty range to max_element -- you won't be able to safely dereference the result.

提交回复
热议问题