难以理解"list<int>::iterator i;"
Trouble understanding "list<int>::iterator i;"
我一直在学习如何让列表在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)
{
}
获取相同的结果。
相关文章:
- EASTL矢量<向量<int>>连续的
- 在调试模式下引发C++ "deque iterator not dereferencable"异常
- std::iterator::reference 必须是引用吗?
- 为什么unordered_set<string::iterator>不起作用?
- 造成致命错误:boost/fusion/iterator/equal_to.hpp 没有这样的文件或目录
- Visual accept std::string from std::byte iterator
- 什么是"std::set<int,int>::iterator"?
- 从 std::vector 中删除项目时"Iterator not incrementable"
- 如何从 boost::container::vector<std::string>::iterator 访问索引和对象?
- 空集"Out of bound iterator"
- 如何使用set<pair<int,int> >::iterator itrator it迭代set<pair<int,int> >st中的值?
- 给定一个类型为 Container:<T>:Iterator 的函数参数,如何为某些类型的 T 实现特定的重载?
- 带升压async_read_some "String iterator not dereferncable"
- C++为什么"deque iterator not dereferencable "
- C - 创建矢量&lt; vector&lt; double&gt;&gt;矩阵具有分配而不是inizializ
- 错误:与'operator='不匹配(操作数类型为"std::map<int、double>::iterator
- 自动,错误:MAP ITERATOR没有名为“ First”的成员
- C 字符串比较“祝您好运”&gt;“再见”
- set<shared_ptr<T>>::iterator to set<shared_ptr<t const>>::const_iterator
- 标准::复制失败,"cannot seek vector iterator after end"