从函数返回变量的链表

Linked list returning variables from a function

本文关键字:链表 变量 返回 函数      更新时间:2023-10-16

嗨,我正在为大学做一个项目,但我被困在一个部分。我在 c++ 中使用链表。我必须设置一个名为 Book 的类,其中包含变量"标题"、"作者"、"ISBN"和"可用性"。我在我的主要版本中使用函数的原型和在其他地方调用的函数来设置它。

//the prototype
list<Book> bookSetUp();
int main()
{
//the variable in main that will have the list
list<Book> bookList;
//the list being populated in function elsewhere so as to not mess up the main
bookList = bookSetUp();
// more stuff in main 
}
//sets up the book vector list by populating it
//title, author, ISBN, availability
list<Book> bookSetUp()
{
//creates a temp vector to pass it back to the actual vector to be used in the main
list<Book> temp;
//The items that populate the list
Book a("A Tale of Two Cities", "Charles Dickens", 1203456, true);
Book b("Lord of the rings", "J.R.R Tolkein", 123456, true);
Book c("Le Petit Prince", "Antoine de Saint-Exupéry", 123457, true);
Book d("And Then There Were None", "Agatha Christie", 123458, true);
Book e("Dream of the Red Chamber","Cao Xueqin",123459, true);
Book f("The Hobbit","J.R.R Tolkein",123467, true);
//pushes the items into the vector
temp.push_back(a);
temp.push_back(b);
temp.push_back(c);
temp.push_back(d);
temp.push_back(e);
temp.push_back(f);
//returns the list
list<Book>::iterator pos;
pos = temp.begin();
while(pos != temp.end())
{
return pos;
if(pos != temp.end())
{
pos++;
}
}
}

我知道文件之间的链接很大,我只是无法获得"临时"列表来返回值。任何帮助将不胜感激。谢谢

C++大多数容器(如std::list)都可以像任何其他基元类型一样进行复制构造或分配。在您的情况下,直接return就足够了。