解决方法:
#include <boost/archive/binary_iarchive.hpp>
#include <boost/archive/binary_oarchive.hpp>
#include <boost/serialization/string.hpp>
#include <boost/serialization/export.hpp>
#include <boost/serialization/vector.hpp>
#include <boost/serialization/list.hpp>
void saveFeaturesFile(vector<vector<float>> &features, string filename){
ofstream out(filename.c_str());
stringstream ss;
boost::archive::binary_oarchive oa(ss);
oa << features;
out << ss.str();
out.close();
}
void loadFeaturesFile(vector<vector<float>> &features, string filename){
ifstream in(filename.c_str());
boost::archive::binary_iarchive ia(in);
ia >> features;
in.close();
}
同时再编译过程中加入相应的boost库
ex:g++ -std=c++11 -o test Test.cpp **-L/usr/local/lib -lboost_iostreams -lboost_serialization**
方法2:
void saveVector(std::string path, const vector<vector<float> >& myVector)
{
std::ofstream FILE(path, std::ios::out | std::ofstream::binary);
// Store size of the outer vector
int s1 = myVector.size();
FILE.write(reinterpret_cast<const char *>(&s1), sizeof(s1));
// Now write each vector one by one
for (auto& v : myVector) {
// Store its size
int size = v.size();
FILE.write(reinterpret_cast<const char *>(&size), sizeof(size));
// Store its contents
FILE.write(reinterpret_cast<const char *>(&v[0]), v.size()*sizeof(float));
}
FILE.close();
}
void readVector(std::string path, vector<vector<float> >& myVector)
{
ifstream FILE(path, std::ios::in | std::ifstream::binary);
int size = 0;
FILE.read(reinterpret_cast<char *>(&size), sizeof(size));
myVector.resize(size);
for (int n = 0; n < size; ++n) {
int size2 = 0;
FILE.read(reinterpret_cast<char *>(&size2), sizeof(size2));
float f;
for ( int k = 0; k < size2; ++k ) {
FILE.read(reinterpret_cast<char *>(&f), sizeof(f));
myVector[n].push_back(f);
}
}
}
来源:https://stackoverflow.com/questions/43230542/write-vectorvectorfloat-to-binary-file
以上两种方法,具体消耗时间未测试。
序列化资料:
https://www.ibm.com/developerworks/cn/aix/library/au-boostserialization/