【问题标题】:Linked list returning variables from a function从函数返回变量的链表
【发布时间】:2013-11-16 20:15:08
【问题描述】:

嗨,我正在为大学做一个项目,但我陷入了困境。我在 C++ 中使用链表。我必须设置一个名为 Book 的类,其中包含变量“title”、“author”、“ISBN”和“availability”。我在 main 中使用函数原型和在其他地方调用的函数进行了这样的设置。

//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++;
}
}
}

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

【问题讨论】:

  • 你想在while(pos != temp.end()) 循环中做什么?它目前立即返回temp.begin()
  • 对大量代码感到抱歉!我觉得这比试图传达所有内容要好
  • 嗯。你到底想做什么?我有一种感觉,你想要像某些语言中的 'yield' 那样的东西
  • 我将 pos 设置为列表的开头 pos = temp.begin(); 以便它递增到列表中的下一个项目,除非它已到达末尾 pos != temp.end() 我正在尝试获取该功能bookSetUp() 填充主列表 bookList 中的列表。我应该在我的问题中说明这一点,主要在 main.cpp 中,而 bookSetUp() 在另一个名为 functions 的.cpp 中。

标签: c++ function linked-list return-value


【解决方案1】:

在 C++ 中,像std::list 这样的大多数容器都可以像任何其他原始类型一样被复制构造或赋值。在您的情况下,直接return 就足够了。

【讨论】:

    猜你喜欢
    • 2016-10-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-24
    • 2018-03-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多