c++:不能给迭代器赋索引
C++: cannot assign index to iterator
好吧,一个小问题,希望有一个快速,简单的解决方案。
在我的学校教科书中,有一章是关于STL的,它给出了一个简单的示例程序来输入使用列表和使用列表迭代器,如下所示:
#include <list>
#include <iostream>
#include <string>
using namespace std;
int main()
{
list<int> myIntList;
// Insert to the front of the list.
myIntList.push_front(4);
myIntList.push_front(3);
myIntList.push_front(2);
myIntList.push_front(1);
// Insert to the back of the list.
myIntList.push_back(5);
myIntList.push_back(7);
myIntList.push_back(8);
myIntList.push_back(9);
// Forgot to add 6 to the list, insert before 7. But first
// we must get an iterator that refers to the position
// we want to insert 6 at. So do a quick linear search
// of the list to find that position.
list<int>::iterator i = 0;
for( i = myIntList.begin(); i != myIntList.end(); ++i )
if( *i == 7 ) break;
// Insert 6 were 7 is (the iterator I refers to the position
// that 7 is located. This does not overwrite 7; rather it
// inserts 6 between 5 and 7.
myIntList.insert(i, 6);
// Print the list to the console window.
for( i = myIntList.begin(); i != myIntList.end(); ++i )
cout << *i << " "; cout << endl;
}
现在,在
那行list<int>::iterator i = 0;
我得到一个错误在VS 2015说:
no suitable constructor exists to convert from"int" to "std::_List_iterator<std::_List_val<std::_List simple_types<int>>>"
所呈现的代码的问题是什么,解决方案是什么,为什么这是一个问题?<-(我甚至会解决一个简单的语法错误)。
值0
可能不是迭代器的有效值。尝试删除赋值或将迭代器赋值给myIntList.begin()
。
迭代器不能像vector
或数组那样被视为索引。通常链表不是通过索引访问的;你必须从头遍历
给出的代码有什么问题
示例中的一个简单的打字错误。
解决方案是什么
替换这一行:
list<int>::iterator i = 0;
用这个代替:
list<int>::iterator i;
为什么这是一个问题?
不能用整数值初始化迭代器。只有容器知道它的迭代器指向什么,所以只有容器可以初始化它们。你所能做的就是从容器请求一个迭代器,将一个迭代器赋值给另一个迭代器,并对一个迭代器进行自增/自减/解引用操作。
From http://www.cplusplus.com/reference/iterator/:
迭代器是指向元素范围(如数组或容器)中的某个元素,能够使用一组操作符(至少使用自增(++)和解引用(*)操作符)遍历该范围内元素的任何对象。
这意味着迭代器应该能够做以下事情:
- 返回当前"指向"的对象(使用
*
操作符) - 将自身更改为"指向"其列表中的下一个对象(使用
++
操作符)
将迭代器作为一种数据类型存在的原因是为了创建一种与不同类型的列表交互的通用方法。然而,这意味着不同的列表将以不同的方式实现它们的迭代器。
在许多情况下,将迭代器初始化为数字是没有意义的,因为在底层实现。因此,不能在迭代器类型std::vector<int>::iterator
的左侧和int
的右侧定义赋值操作符。因此,当你尝试将迭代器赋值给整型值时,list<int>::iterator i = 0;
编译器会抛出错误。
让我们看一个将迭代器赋值给0
没有意义的例子。可以为std::vector<int>
实现一个迭代器,作为指向vector中的元素的指针。在本例中:
-
*
对存储在vector<int>::iterator
中的指针解引用并返回其值。 -
++
修改存储在vector<int>::iterator
中的指针,使其指向列表中下一个元素。
然而,将此指针赋值给0
将与将其赋值给NULL
相同,并且对其解引用不再返回vector中的有效元素。(实际上,解引用NULL
会导致错误!)
要避免此错误,只需确保始终将迭代器赋值给相同类型的值。在STL中,这通常是通过使用.begin()
返回指向列表中第一个元素的迭代器来完成的。
- 跟随整数索引列表的自定义类迭代器
- 为什么 min_element() 返回最小元素的索引,而不是迭代器?
- 在擦除或修改作为不同索引键的值时,boost::multi_index 迭代器是否无效?
- C++将向量迭代器转换为索引
- 使用索引与迭代器将向量迭代到倒数第二个元素
- 如何使equal_range迭代器在 Boost 多索引中按不同的索引排序?
- 仅在使用迭代器的某些索引上生成值
- 是否可以在C++中获得索引迭代器?
- 有没有办法创建一个花哨的迭代器和相应的新数组,以便检查每个索引的索引值的条件?
- 索引与迭代器 - 哪个更有效?
- C 迭代器比索引慢得多
- 存储Boost Multi_index索引迭代器
- 属性树常量迭代器的索引
- 矢量迭代器的索引
- 提升多索引有序迭代器分配
- 使用迭代器的矢量擦除特定索引(不基于范围或条件)
- 为什么boost多索引返回错误的迭代器
- 从迭代器获取索引处的元素
- Deque索引迭代器转换
- Boost C++ 中的索引子集迭代器