如何在 c++ 中打印存档中的对象向量
How to print a vector of objects from an archive in c++
我的代码应该读取一个文件,并从该文件上的信息创建类 Movie 和 将它们存储在矢量中,现在它们在矢量中,我如何打印这些对象?
void Movie::loadFile(string file)
{
ifstream inFile;
inFile.open(file+".txt");
try {
if (!inFile)
throw "UNABLE TO OPEN FILE";
}catch (const char* msg)
{
cerr << msg << endl;
exit(1);
}
while (inFile.good())
{
getline(inFile, id, ',');
getline(inFile, name, ',');
getline(inFile, tim, ',');
getline(inFile, gen, ',');
getline(inFile, rate, 'n');
mov.push_back(new Movie(id, name, tim, gen, rate));
}
inFile.close();
cout<<endl;
}
我试图通过重载运算符来做到这一点,但我得到错误
error: 'std::vector<Movie*> Movie::mov' is protected within this context
error: 'ostream_iterator' was not declared in this scope
error: expected primary-expression before '>' token
ostream &operator <<(ostream& salida, const Movie& print)
{
salida << print.id << endl;
copy(print.mov.begin(), print.mov.end(), ostream_iterator<Video>(salida, " "));
return salida;
}
我真的会感谢帮助:)。
为了使用
copy(print.mov.begin(), print.mov.end(), ostream_iterator<Video>(salida, " "));
您需要实现以下重载。
std::ostream& operator<<(std::ostream&, Video const&);
从 https://en.cppreference.com/w/cpp/iterator/ostream_iterator:
std::ostream_iterator
是一个单通道LegacyOutputIterator,它使用operator<<
将类型为T
的连续对象写入为其构造的std::basic_ostream
对象中。
相关文章:
- 为什么我不能将一个对象push_back到属于另一个类的对象向量中?
- 从多个源构造一个对象,包括一个对象向量
- 如何从文件中读取两个字符串和数字数组,并将它们存储在对象向量中
- 对象 C++ 向量的 STL 容器
- 初始化C++中的对象向量
- 从自定义类获取对象向量中的 max 元素
- 如何在 c++ 中打印存档中的对象向量
- 如何将包含另一个对象向量的对象保存到文件中,并使用C++中的二进制文件从文件中读回?
- 尝试重载输出运算符时,我无法遍历对象向量
- 如何在C++中打印对象向量的内容
- 打印出对象向量中的每个元素C++
- 在 c++ 的构造函数中分配对象向量时出错
- 遍历对象向量,并找到与从文本文件中提取的对象匹配的变量
- 对象向量是否在堆或堆栈上分配C++?
- 基于不同字段的对象向量的排序功能
- 有没有一种简单的方法可以在对象向量上调用构造函数?
- 用rapidjson读取子对象向量
- 尝试使用比较运算符对对象向量进行排序
- 如何用对象向量重载 cin(>>)
- 如何将某个元素从shared_ptr擦除到对象向量?