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>());
Don't use
thrust::reduce
. Usethrust::max_element
(thrust::min_element
) inthrust/extrema.h
:Be careful when passing an empty range to
max_element
-- you won't be able to safely dereference the result.Jared Hoberock has already satisfactorily answered this question. I want to provide below a slight change to account for the common case when the array has been allocated by
cudaMalloc
and not through adevice_vector
container.The idea is to wrap a
device_pointer
dev_ptr
around thecudaMalloc
'ed raw pointer, casting the output ofmin_element
(I'm considering the minimum instead of the maximum without any loss of generality) to adevice_pointer
min_ptr
and then finding the minimum value asmin_ptr[0]
and the position by&min_ptr[0] - &dev_ptr[0]
.