list<Book>::iterator pos;
pos = books.begin();
books.begin()->setPrevBook(NULL);
for (pos = books.begin(); pos != books.end(); pos++)
{
cout << book.getTitle() << "\n"
<< book.getAuthor() << "\n"
<< book.getISBN() << "\n"
//I'd like to set the next and previous books here
//<< book.setNextBook()
//<<book.setPrevBook()
<< "******************************" << endl;
}
这是我的书的迭代器,我的程序经历循环,直到用户告诉它停止然后它打印出所有的书。
我的书也有这个代码
void Book::setNextBook(Book* nextBookParam)
{
nextBook = nextBookParam;
}
Book* Book::getNextBook() const
{
return nextBook;
}
void Book::setPrevBook(Book* prevBookParam)
{
prevBook = prevBookParam;
}
Book* Book::getPrevBook() const
{
return prevBook;
}
我想在我的列表迭代器中做的是,当它完成添加新书时,将下一本书添加到即将添加的书中,将之前的书添加到刚刚添加的书中。基本上,我想将所有书籍连在一起。
我有办法做到这一点吗?
任何帮助表示感谢。
答案 0 :(得分:1)
如果我理解正确,那么您正尝试使用存储在books
类中的指针重新创建双向链接列表Book
。这似乎有点浪费精力,但如果你需要它,你有两种选择。
您可以在循环中使用额外的迭代器来指向“最后”的书:
list<Book>::iterator pos, last;
books.begin()->setPrevBook(NULL);
for (pos = books.begin(); pos != books.end(); ++pos)
{
cout << pos->getTitle() << "\n"
<< pos->getAuthor() << "\n"
<< pos->getISBN() << "\n"
<< "******************************" << endl;
if (pos != books.begin())
{
last->setNextBook(&*pos);
pos->setPrevBook(&*last);
}
last = pos;
}
books.back().setNextBook(NULL);
使用指向最后一本书而不是迭代器的指针:
list<Book>::iterator pos;
books.begin()->setPrevBook(NULL);
Book *last = NULL;
for (pos = books.begin(); pos != books.end(); ++pos)
{
cout << pos->getTitle() << "\n"
<< pos->getAuthor() << "\n"
<< pos->getISBN() << "\n"
<< "******************************" << endl;
if (last)
{
last->setNextBook(&*pos);
pos->setPrevBook(last);
}
last = &*pos;
}
books.back().setNextBook(NULL);
答案 1 :(得分:0)
怎么样?
auto book = books->begin();
book ->setPreviousBook(NULL);
auto prev = book;
++book;
while(book != books->end()) {
book->setPreviousBook(&*prev);
prev->setNextBook(&*book);
++book;
++prev;
}
prev->setNextBook(NULL);