c++:不能给迭代器赋索引

C++: cannot assign index to iterator

本文关键字:索引 迭代器 不能 c++      更新时间:2023-10-16

好吧,一个小问题,希望有一个快速,简单的解决方案。

在我的学校教科书中,有一章是关于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/:

迭代器是指向元素范围(如数组或容器)中的某个元素,能够使用一组操作符(至少使用自增(++)和解引用(*)操作符)遍历该范围内元素的任何对象。

这意味着迭代器应该能够做以下事情:

  1. 返回当前"指向"的对象(使用*操作符)
  2. 将自身更改为"指向"其列表中的下一个对象(使用++操作符)

将迭代器作为一种数据类型存在的原因是为了创建一种与不同类型的列表交互的通用方法。然而,这意味着不同的列表将以不同的方式实现它们的迭代器。

在许多情况下,将迭代器初始化为数字是没有意义的,因为在底层实现。因此,不能在迭代器类型std::vector<int>::iterator的左侧和int的右侧定义赋值操作符。因此,当你尝试将迭代器赋值给整型值时,list<int>::iterator i = 0;编译器会抛出错误。

让我们看一个将迭代器赋值给0没有意义的例子。可以为std::vector<int>实现一个迭代器,作为指向vector中的元素的指针。在本例中:

  1. *对存储在vector<int>::iterator中的指针解引用并返回其值。
  2. ++修改存储在vector<int>::iterator中的指针,使其指向列表中下一个元素。

然而,将此指针赋值给0将与将其赋值给NULL相同,并且对其解引用不再返回vector中的有效元素。(实际上,解引用NULL会导致错误!)

要避免此错误,只需确保始终将迭代器赋值给相同类型的值。在STL中,这通常是通过使用.begin()返回指向列表中第一个元素的迭代器来完成的。