How to concatenate two tensors in C++ API


I am new to pytorch, and I want to use pytorch to train with a C++ simulation program in an automated alternating working flow, so I am learning to use PyTorch C++ API.

I went through some try-and-error and was able to get examples with the simplest type of neutral networks working. When I want to try some more complicated examples, I found myself needing to concatenate tensors in the forward function, and I was not able to find the way to do so, therefore that become my first question here.

Also, is there a good documentation about the interface, like what public methods/operators are available for torch::Tensor class, etc.? I couldn’t find many such info in the “Library API” section on the website (I wasn’t able to even find the torch::Tensor class there). Or maybe I am missing something?


I seem to have figured it out.

torch::cat({x, y}) seem to work for me, not 100% sure about the requirements on the dimensionality. It looks like there is a version with another parameter to specify the dimension but it says I can only use -1 or 0, and I am not sure what that means. At least it works as expected when I just concatenate two 1D tensors together.

1 Like

Yes it’s torch::cat.

You can indeed specify the dimension along which to concatenate. In this case -1 means the last one.
So for 1D tensor you can pass -1 or 0 but it will have the same effect

I see. Thanks for the clarification.