4.4. From/To C++.vectorΒΆ

Cytnx provides a way to convert directly between a C++ vector and a Storage instance.

To convert a C++ vector to a Storage, use Storage::from_vector:

  • In C++:

1vector<double> vA(4, 6);
2
3auto A = cytnx::Storage::from_vector(vA);
4auto B = cytnx::Storage::from_vector(vA, cytnx::Device.cuda);
5
6cout << A << endl;
7cout << B << endl;

Output >>

dtype : Double (Float64)
device: cytnx device: CPU
size  : 4
[ 6.00000e+00 6.00000e+00 6.00000e+00 6.00000e+00 ]

dtype : Double (Float64)
device: cytnx device: CUDA/GPU-id:0
size  : 4
[ 6.00000e+00 6.00000e+00 6.00000e+00 6.00000e+00 ]

Note

You can also specify the device upon calling from_vector.

Tip

Cytnx overloads the operator<< for C++ vectors. You can directly print any vector when using namespace cytnx;. Alternatively, you can also use the print() function just like in Python.

[New][v0.7.5+] To convert a Storage to std::vector with type T, use Storage.vector<T>():

  • In C++:

1Storage sA = {3., 4., 5., 6.};
2
3print(sA.dtype_str());
4
5auto vA = sA.vector<double>();
6
7print(vA);

Output >>

Double (Float64)
Vector Print:
Total Elements:4
[3, 4, 5, 6]

Note

The type T has to match the dtype of the Storage, otherwise an error will be raised.