将指针向量存储在文件中并再次读取它们
Storing vector of pointers in a file and reading them again
>假设以下代码:
// Base class
class Base {
public:
Base(int val) : hi(val) {
}
virtual void PublicMethod() { /* Do something */}
private:
int hi;
};
// Child class
class Child : public Base {
public:
Child(int val) : Base(val) {
}
void PublicMethod() { /* Do something */}
};
// Vector of pointers to prevent slicing
std::vector<std::shared_ptr<Base>> list;
(...) // Fill list with mixed data of class Base and Child
在列表中填充对象后,我想将数据存储到文件中。为此,我尝试了以下方法:
std::ofstream os("data.txt", std::ios::out);
int size1 = list.size();
os.write((const char*)&size1, sizeof(int));
for (auto it = list.begin(); it < list.end(); ++it) {
os.write((const char*)(*it), size1 * sizeof(Base));
}
os.close();
但是,我不确定这是否正确,并且从文件中读取数据似乎也无法正常工作。恐怕当我保存数据时,sizeof(Base)
也不适用于可能大小不同的子对象。
即使这工作正常,是否有更好的方法将实际数据存储到文件中,以及如何轻松地从文件中读取数据并将它们存储在shared_ptr<Base>
向量列表中?
任何例子都会有很大帮助。
您需要为对象提供某种形式的序列化。 这是一个非常简单的示例(省略了错误检查,类型构造等)
此示例显示了大多数基元类型的序列化,但它足以提供您需要执行的操作的示例。
当您开始处理派生类时,它会变得更加棘手,因为您将需要一些工厂方法来基于序列化的某些哨兵值正确创建类型。
#include <string>
#include <iostream>
#include <sstream>
using namespace std;
class A
{
public:
A()
: a_(0)
{
}
A(int a, const string& n)
: a_(a), n_(n)
{
}
// a function to write objects to a stream
friend ostream& operator<<(ostream& stream, const A& obj);
// a function to read objects from a stream
friend istream& operator>>(istream& stream, A& obj);
private:
int a_;
string n_;
};
ostream& operator<<(ostream& out, const A& obj)
{
out << obj.a_ << ' ' << obj.n_;
return out;
}
istream& operator>>(istream& in, A& obj)
{
in >> obj.a_ >> obj.n_;
return in;
}
int main()
{
A one(1, "one");
A also_one;
string buffer;
stringstream serializer;
// write out your source object to a stream and "store it"
// here we simply store it in a string
serializer << one;
buffer = serializer.str();
// using the "stored" value, read the stored values
// into an (already constructed) object
stringstream deserializer(buffer);
serializer >> also_one;
// verify the output is the same
cout << one << " is the same as " << also_one << "n";
}
相关文章:
- C++:如何读取分离变量,然后读取向量
- C++读取行到类向量
- 如何从文件中读取两个字符串和数字数组,并将它们存储在对象向量中
- 从流到邻接列表的向量读取图形
- 尝试将字符串从文件读取到无符号字符向量中
- 如何在 c++ 中从字符串向量中读取
- 将结构向量保存到文件中,并从C++文件中读取结构向量
- C++,从文件读取到结构,然后读取到向量(结构被推入向量太多次,而不仅仅是一次)
- 从.txt文件读取到C++中的双精度向量
- 用rapidjson读取子对象向量
- 对唯一 ptr 无效读取的引用向量
- 如何从输入文件中读取字符并将其存储到向量中?
- 如何使用 cin 将整数从控制台读取到向量中
- 无法使用迭代器在类对象的向量中读取向量
- 提升ASIO写入/读取向量
- 试图从文本文件中读取向量
- 我可以读取向量<string>::迭代器的数字位置吗?
- 重载 C++ 运算符>>,以便我可以读取向量(向量<int>向量;
- 按值与按引用读取C++向量
- 从文件中读取向量、结构和While循环