c++ - 打印列表中的元素

标签 c++ list loops

Book Administrator::bookDetails()
{
    Book book;
    list<Book> books;

    string title;
    string author;
    int ISBN;

    string userInput;

    while (userInput != "q")
    {
        cout << "Would you like to enter a book?" << endl;
        cin >> userInput;
        if (userInput == "yes")
        {
            cout << "What is the title of the book you want to enter?" << endl;
            cin >> title;

            cout << "What is the author of the book you want to enter?" << endl;
            cin >> author;

            cout << "What is the ISBN of the book you want to enter?" << endl;
            cin >> ISBN;

            book.setTitle(title);
            book.setAuthor(author);
            book.setISBN(ISBN);

            books.push_back(book);

        }

        list<Book>::iterator pos;
        pos = books.begin();

        for (pos = books.begin(); pos != books.end(); pos++)
        {
                    //There error is produced here
            cout << *pos << "\n";
        }

    }
    return book;
}

这是我的管理类的 bookDetails 函数。它循环遍历并询问书名、作者和 ISBN 号,完成后将书推送到列表中。

这在我调试时似乎工作正常,但当我尝试使用迭代器打印每本书的详细信息时出现错误。

有人可以帮我吗? 谢谢

最佳答案

您需要实现 operator<<对于 Book

std::ostream operator<<(std::ostream& os, const Book& book)
{
   os << book.title << " " << book.author; // print out other information
   return os;
}

关于c++ - 打印列表中的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20156352/

相关文章:

c++ - 如何缩放到 SDL 中的分辨率?

c++ - 在 STL 列表中找到一对,其中只有第一个元素是已知的

arrays - 使用 R 将文件导入数组

c++ - 检查哪个模块最接近

Python如何证明循环中的 boolean 表达式并在单击按钮时取消循环

c++ - 为什么 C++ 库的地址清理构建会在 libcxx 类中产生不可重现的 ASAN 问题?

c++ - 未命名的命名空间与私有(private)变量

c++ - 使用 boost::iostreams::tee_device?

c# - 如何获得内部列表计数?

C# 在 List<T> 索引处添加值的方法