我需要将矢量矢量保存到文件并读取它们我尝试使用此代码但发生错误:
void saveVector(std::string path, vector<vector<float>> myVector)
{
std::ofstream FILE(path, std::ios::out | std::ofstream::binary);
std::copy(myVector.begin(), myVector.end(), std::ostreambuf_iterator<char>(FILE));
FILE.close();
}
错误:
Error C2679 binary '<<': no operator found which takes a right-hand operand of type 'std::vector<float,std::allocator<_Ty>>' (or there is no acceptable conversion)
答案 0 :(得分:4)
你在那里做什么......这是世界上最糟糕的想法!您正在编写可能依赖于编译器和编译器版本的数据。这是因为向量不仅包含数组,而是包含其他变量,例如向量的大小。标准未指定顺序,因此二进制形式将依赖于编译器。
您有很多选择可以避免这种情况:
vector<float>
如果你使用的是C ++ 03,那么你应该使用类型:vector<vector<float> >
,而不是vector<vector<float>>
。
也通过引用传递这些对象以避免复制它们。像这样:
void saveVector(const std::string& path, const vector<vector<float>>& myVector)
答案 1 :(得分:1)
在这一行:
std::copy(myVector.begin(), myVector.end(), std::ostreambuf_iterator<char>(FILE));
您希望std::ostreambuf_iterator<char>
知道如何将std::vector<float>
写入流,但它只知道如何编写o char
类型,请在此处查看其赋值运算符:{{3} }
我会手动完成:
http://en.cppreference.com/w/cpp/iterator/ostreambuf_iterator/operator%3D
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);
}
}
}
int main()
{
std::vector<std::vector<float>> ff;
ff.resize(10);
ff[0].push_back(10);
ff[0].push_back(12);
saveVector("test.bin", ff);
std::vector<std::vector<float>> ff2;
readVector("test.bin", ff2);
if (ff == ff2) {
std::cout << "ok!";
}
}