我一直在研究如何使列表在 C++ 中工作。尽管第 12 行不起作用,但我对标题中提到的行更感兴趣,因为我不明白这是做什么的?
因此,for循环中存在错误,但我认为这是由于我对 缺乏了解list<int>::iterator i;,如果有人能够分解并解释这条线对我意味着什么,那就太棒了!
#include <iostream>
#include <list>
using namespace std;
int main(){
list<int> integer_list;
integer_list.push_back(0); //Adds a new element to the end of the list.
integer_list.push_front(0); //Adds a new elements to the front of the list.
integer_list (++integer_list.begin(),2); // Insert '2' before the position of first argument.
integer_list.push_back(5);
integer_list.push_back(6);
list <int>::iterator i;
for (i = integer_list; i != integer_list.end(); ++i)
{
cout << *i << " ";
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
此代码直接取自此处。只有列表的名称已更改。
该list<int>::iterator类型是模板化类的迭代器类型list<int>。迭代器允许您一次查看列表中的每个元素。修复您的代码并尝试解释,这是正确的语法:
for (i = integer_list.begin(); i != integer_list.end(); ++i)
{
// 'i' will equal each element in the list in turn
}
Run Code Online (Sandbox Code Playgroud)
该方法list<int>.begin()和list<int>.end()每个返回实例分别list<int>::iterator指向列表的开头和结尾。for 循环中的第一项list<int>::iterator使用复制构造函数将您初始化为指向列表的开头。第二项检查您的迭代器是否与指向末尾的迭代器指向的位置相同(换句话说,您是否已经到达列表的末尾),第三项是运算符重载的示例。该类list<int>::iterator重载了++操作符,使其表现得像一个指针:指向列表中的下一项。
您还可以使用一些语法糖并使用:
for (auto& i : integer_list)
{
}
Run Code Online (Sandbox Code Playgroud)
为了同样的结果。希望这可以为您清除一些迭代器。