Search code examples
c++pytorchlibtorch

Copy a chunk of one tensor into another one in C++ API


I need to copy a row of one tensor (in c++ API) into some part of another tensor, form which the begin and end indexes are available. Within C++ we can use something like:

int myints[] = {10, 20, 30, 40, 50, 60, 70};
std::vector<int> myvector(18);

std::copy(myints, myints + 3, myvector.begin() + 4);

to copy three values from myints into myvector, starting at the fourth index. I was wondering if there is a similar API in libtorch (i.e., C++)?


Solution

  • The C++ API provides the Python slice equivalent function

    at::Tensor at::Tensor::slice(int64_t dim, int64_t start, int64_t end, int64_t step);
    

    You can thus do something like:

    auto myints = torch::Tensor({10, 20, 30, 40, 50, 60, 70});
    auto myvector = torch::ones({18});
    
    myvector.slice(0, 3, 7) = myints.slice(0, 0, 3);
    

    in your case using dim=0 first dimension