Creating a DimnameList from an std::vector<std::string> in C++

How can I create a DimnameList from a vector of strings in C++?

I am trying something like:

torch::DimnameList cpp_torch_dimname_list (std::vector<std::string> x) {
 
 std::vector<torch::Dimname> out;
 
 for (int i = 0; i < x.size(); ++i) {
   out.push_back(torch::Dimname::fromSymbol(torch::Symbol::dimname(x[i])));
 }
 
return out;
}

But this is not working as expected…

Maybe this code snippet can help you: :wink:

#include <torch/torch.h>
#include <torch/script.h>
#include <array>
#include <iostream>
#include <iomanip>

torch::Dimname dimnameFromString(const std::string& str);

int main()
{

	std::cout << std::fixed << std::setprecision(4);

	auto options =
	    torch::TensorOptions()
	    .dtype(torch::kFloat32);

	auto r = dimnameFromString("r"); // name of the first dimension
	auto c = dimnameFromString("c"); // name of the second dimension

	std::vector<torch::Dimname> names = { r, c }; // put them into a vector

	auto z_ = torch::zeros({5, 5}, names,options); // make a dummy zeros tensor
	std::array<torch::Tensor, 2> arrayRefz_ = {z_, z_}; // make a arrayRef

	auto cat_out_z = at::cat(arrayRefz_, c); // concatinate besed on the dimension names
	std::cout << z_.names() << std::endl; // print the dimension names

	std::cout << "Concatinate z_ with z_: \n" << cat_out_z  << std::endl;
}

torch::Dimname dimnameFromString(const std::string& str) {
	return torch::Dimname::fromSymbol(torch::Symbol::dimname(str));
}