Finding the maximum element value AND its position using CUDA Thrust

rych picture rych · Oct 10, 2011 · Viewed 9.2k times · Source

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<float> h_vec(100);
thrust::generate(h_vec.begin(), h_vec.end(), rand);
thrust::device_vector<float> d_vec = h_vec;

T res = -1;
res = thrust::reduce(d_vec.begin(), d_vec.end(), res, thrust::maximum<T>());

Answer

Jared Hoberock picture Jared Hoberock · Oct 10, 2011

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

thrust::host_vector<float> h_vec(100);
thrust::generate(h_vec.begin(), h_vec.end(), rand);
thrust::device_vector<float> d_vec = h_vec;

thrust::device_vector<float>::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.