难以理解"list<int>::iterator i;"

Trouble understanding "list<int>::iterator i;"

本文关键字:gt iterator int list lt      更新时间:2023-10-16

我一直在学习如何让列表在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;
}

这段代码直接取自这里。

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
}

方法list<int>.begin()list<int>.end()各自返回list<int>::iterator的实例,分别指向列表的开始和结束。for循环中的第一个项使用复制构造函数初始化list<int>::iterator,使其指向列表的开头。第二项检查迭代器指向的位置是否与指向末端的迭代器指向的位置相同(换句话说,是否到达了列表的末端),第三项是操作符重载的一个例子。类list<int>::iterator重载了++操作符,使其行为类似于指针:指向列表中的下一项。

你也可以使用一点语法糖,使用:

for (auto& i : integer_list)
{
}

获取相同的结果。