递增解引用迭代器

Incrementing Dereferenced Iterator

我正在做 C++ 入门练习 (3.25),我正在尝试增加一个取消引用的迭代器。这是我的想法:

vector <int> arcNotas(10,0);        //hold amount of grades by 10-20-30....90-100
int notas = 0;
auto it = arcNotas.begin();
while (cin >> notas && notas!= 1000) {
    it += notas / 10;                   //move the iterator to the right position
    *it++;                              //increment the quantity of elements in that position
    it = arcNotas.begin();              //reset to the initial position
}

但是当我编译它时,编译器说(在第一个 "notes" 输入之后)“vector 迭代器不可递增”。我正在取消引用 it 专门为此...我只是不明白哪里出了问题。我进行了搜索,但我发现的只是递增 it 的问题,而不是 *it.

您的问题是运算符优先级之一。简而言之,您的行 *it++; 是错误的。这相当于写 *(it++),它将在首先评估 ++ 运算符后提供旧值,然后取消引用它。

相反,您要做的是先取消引用 it,然后通过写入 (*it)++ 来增加值。这是因为 ++ 运算符的优先级高于间接运算符 *.

我将用文档化的代码示例进行说明:

#include <iostream>
#include <vector>
using namespace std;

int main()
{
    vector<int> grades(5, 0);
    auto it = grades.begin();

    cout << "Show initial elements before increment..." << endl;
    while(it != grades.end()) {
        cout << *it << endl;

        // operator precedence is important;
        // ++ has higher precedence than * for indirection;
        // therefore the observable side-effects are that:
        (*it)++;    // ...this increments the current element pointed by 'it'
        *it++;      // ...this causes 'it' to point to the next element after the old value has been dereferenced w/o additional side-effect
    }

    cout << endl << "Show incremented elements..." << endl;
    it = grades.begin();
    while(it != grades.end()) {
        // notice that elements have been incremented only once by this point
        // not twice as the operator precedence mistake would lead you to believe
        cout << *it << endl;
        it++;
    }

    return 0;
}

构建此程序的命令 (GNU/Linux) 及其输出如下:

➜  /tmp  g++ -std=c++11 test.cpp -o test
➜  /tmp  ./test
Show initial elements before increment...
0
0
0
0
0

Show incremented elements...
1
1
1
1
1

请注意,值只增加一次,而不是两次,考虑到您目前的误解,您可能已经预料到了。

"iterator not incrementable" 消息是一个 运行时 错误。是您的实现对迭代器进行边界检查,并且检测到:

it += notas / 10;

或以下 it++ 导致 it 超出 arcNotas.end()

您应该修复代码以在执行此添加之前检查长度,并修复递增迭代器而不是首先取消引用的问题。