How can I save and load a vector of a vectors of tensors?

How can I save and load a vector of a vectors of tensors?

This is my attempt to save to disk and retrieve. It just returns a random looking number when it should return the vector of vectors of tensors.

#include <fstream>
#include <iterator>
#include <string>

#include <torch/torch.h>
using namespace torch::indexing;
torch::Device device(torch::kCUDA);

std::vector<std::vector<torch::Tensor>> vec_of_vec_of_tensor;
std::vector<torch::Tensor> vec_of_tensor;

class ValueGet {
public:
   int data;
   ValueGet() {
   data = 0;
   }
};

int main() {

    auto foo = torch::rand({3, 3});
    auto foo_two = torch::rand({3, 3});

    vec_of_tensor.push_back(foo);
    vec_of_tensor.push_back(foo_two);
    vec_of_vec_of_tensor.push_back(vec_of_tensor);

    std::cout << vec_of_vec_of_tensor;


    std::ofstream outfile("outfile.dat", std::ofstream::binary);
    outfile.write(reinterpret_cast<const char*>(vec_of_vec_of_tensor.data() /* or &v[0] pre-C++11 */), sizeof(int) * vec_of_vec_of_tensor.size());
    outfile.close();

    ValueGet vg;
    std::ifstream file;
    file.open("outfile.dat", std::fstream::binary | std::fstream::out); // Opens a file in binary mode for input operations i.e., getting data from file.
    if (!file)
        std::cout << "File Not Found.";
    else {
        file.seekg(0); // To make sure that the data is read from the starting position of the file.
        while (file.read((char *)&vg, sizeof(vg))) // Iterates through the file till the pointer reads the last line of the file.
            std::cout<<vg.data;
    }
}
1 Like