[英]How to print a vector of objects from an archive in c++
My code is supposed to read a file and from the information on that file create objects of class Movie and store them in a vector, How can I print those objects now that they are in the vector?我的代码应该读取一个文件,并从该文件上的信息中创建 class 电影的对象并将它们存储在向量中,既然它们在向量中,我该如何打印这些对象?
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;
}
I have tried to do it by overloading an operator but I get the errors我试图通过重载运算符来做到这一点,但我得到了错误
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;
}
I would really aprecciate the help:).我真的很感激帮助:)。
In order to use为了使用
copy(print.mov.begin(), print.mov.end(), ostream_iterator<Video>(salida, " "));
you need to implement the following overload.您需要实现以下重载。
std::ostream& operator<<(std::ostream&, Video const&);
From https://en.cppreference.com/w/cpp/iterator/ostream_iterator :从https://en.cppreference.com/w/cpp/iterator/ostream_iterator :
std::ostream_iterator
is a single-pass LegacyOutputIterator that writes successive objects of typeT
into thestd::basic_ostream
object for which it was constructed, usingoperator<<
.std::ostream_iterator
是一个单通道LegacyOutputIterator ,它使用operator<<
将T
类型的连续对象写入为其构造的std::basic_ostream
object。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.