Search code examples
c++gputhrust

Thrust inplace copy_if operation


I wanted to know if you can use copy_if as an in-place operation?

i.e.

void copy(thrust::device_vector<int> & input){
    auto end = thrust::copy_if(input.begin(), input.end(), input.begin(), thrust::placeholder.1_ < 10);
        input.erase(end, input.end());
}

is equivalent to:

void copy(thrust::device_vector<int> & input){
        thrust::device_vector<FullOptixRayPayload> dest(input.size());
        auto destEnd = thrust::copy_if(input.begin(), input.end(), dest.begin(), thrust::placeholder.1_ < 10);
        dest.erase(destEnd, dest.end());
        input = dest;
}

(order does not matter to me. I just want to reduce the amount of device space allocation. The copy_if operation and data types are just placeholders)


Solution

  • According to the documentation:

    Preconditions: The ranges [first, last) and [result, result + (last - first)) shall not overlap.

    So no, one is not allowed to use thrust::copy_f in-place. The reason is probably that the algorithm would need to create an internal copy (especially costly due to the potential allocation) before scattering the data to the right positions safely.