法1:转为字符串并用逗号分割,这里使用的是qt的库
//序列化
std::vector<float>m{-0.274489, 0.535285, -1.53439, -0.870895, 0.798769, -0.199406, -0.506447};
QString after="";
for(auto each:m)
{
after=after+QString::number(each, 'g', 6)+",";
}
after.chop(1);
qDebug()<<after;
//反序列化
auto list=after.split(",");
std::vector<float>newone;
for(auto each:list)
{
newone.push_back(each.toDouble());
qDebug()<<each.toDouble();
}
法2:该法中,中间序列化得到的std::string,不要与qstring交互,不然会出错
std::stringstream oss;
std::vector<float>m{0.03,0.56,0.89,0.72,0.56,0.99};
serialize<float>(oss, m);
std::string a=oss.str();
//反序列化
std::stringstream newone;
newone<<a;
std::vector<float>newV;
deserialize<float>(newone,newV);
for(auto each:newV)
{
qDebug()<<each<<" ";
}
qDebug()<<"modelBuild"<<time.elapsed()<<"ms";
辅助函数:
template<typename POD>
std::ostream& serialize(std::ostream& os, std::vector<POD> const& v)
{
// this only works on built in data types (PODs)
static_assert(std::is_trivial<POD>::value && std::is_standard_layout<POD>::value,
"Can only serialize POD types with this function");
auto size = v.size();
os.write(reinterpret_cast<char const*>(&size), sizeof(size));
os.write(reinterpret_cast<char const*>(v.data()), v.size() * sizeof(POD));
return os;
}
template<typename POD>
std::istream& deserialize(std::istream& is, std::vector<POD>& v)
{
static_assert(std::is_trivial<POD>::value && std::is_standard_layout<POD>::value,
"Can only deserialize POD types with this function");
decltype(v.size()) size;
is.read(reinterpret_cast<char*>(&size), sizeof(size));
v.resize(size);
is.read(reinterpret_cast<char*>(v.data()), v.size() * sizeof(POD));
return is;
}