我正在做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
。
"iterator not incrementable"消息是运行时错误。这是你的实现在迭代器上做边界检查,它已经检测到:
it += notas / 10;
或后面的it++
导致it
超越arcNotas.end()
。
你应该修改你的代码,在做这个加法之前检查长度,以及修复你递增迭代器而不是先解引用的问题。
您的问题是操作符优先级之一。简而言之,你的*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
请注意,这些值只增加一次,而不是两次,考虑到您目前的误解,这可能是您期望的。