迭代列表(list :: begin()和list :: end()函数的示例)| C ++ STL
给定一个列表,我们必须对其所有元素进行迭代,并在C++中以新行打印。
示例
Input: list num{10, 20, 30, 40, 50} Output: List elements are: 10 20 30 40 50
列表迭代器
要在C++STL中迭代列表,我们需要一个迭代器,该迭代器应使用列表的第一个元素进行初始化,并且需要对其进行检查,直到列表末尾为止。
列出迭代器声明:
list::iterator it;
list::begin()和list::end()函数
函数list::begin()返回指向第一个元素的迭代器,即返回对第一个元素的引用,而list::end()返回指向最后一个元素的迭代器。
语法:
list_name.begin(); list_name.end();
程序:
#include <iostream> #include <list> using namespace std; int main() { //声明列表 list<int>num {10, 20, 30, 40, 50}; //声明一个参与者 list<int>::iterator it; //使用运行循环begin()end()functons cout<< "List elements are: " <<endl; for ( it=num.begin (); it!=num.end (); it++) cout<< *it <<endl; return 0; }
输出结果
List elements are: 10 20 30 40 50