I use QDataStream to write the variable to .dat file, so the variable I'm writing should be in the form of QVector or QVector2D
vector<vector<int>> vec;
// save
QFile file("save.dat");
file.open(QIODevice::WriteOnly);
QDataStream out(&file);
out << QVector2D<int>::fromStdVector(vec);
// load
QFile file("save.dat");
file.open(QIODevice::ReadOnly);
QDataStream in(&file);
QVector2D<int> qqi;
in >> qqi; vec = qqi.toStdVector();
Error: QVector2D is not a template: out << ...
You don't need to use Qt types to write into the datastream. Just serialize the data in vec
. For that to work you also need to store the sizes of the structures.
int
main( int argc, char** argv ) {
std::vector<std::vector<int>> vec;
vec.resize( 2 );
vec[0] = { 1, 2 };
vec[1] = { 3, 4, 5 };
// save
{
QFile file( "save.dat" );
file.open( QIODevice::WriteOnly );
QDataStream out( &file );
out << vec.size();
for( auto& inner : vec ) {
out << inner.size();
out.writeBytes(
reinterpret_cast<const char*>( inner.data() ),
inner.size() * sizeof( int ) );
}
}
vec.clear();
{
// load
QFile file( "save.dat" );
file.open( QIODevice::ReadOnly );
QDataStream in( &file );
size_t num;
in >> num;
vec.resize( num );
for( auto& inner : vec ) {
in >> num;
inner.resize( num );
auto buffer = reinterpret_cast<char*>( inner.data() );
uint bytes = num * sizeof( int );
in.readBytes( buffer, bytes );
}
}
}