递增解引用迭代器
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
。
"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
请注意,这些值只增加一次,而不是两次,考虑到您目前的误解,这可能是您期望的。
相关文章:
- 不明白迭代器,引用和指针失效,一个例子
- boost_multi_index迭代器取消引用给出常量
- 为什么"std::uninitialized_copy"通常取消对未初始化内存的迭代器的引用不是未定
- 矢量迭代器不能与 std::shared_ptr<> 取消引用
- 无法取消引用值初始化迭代器
- std::remove() 按预期处理文字,但不能与取消引用的迭代器一起工作
- C++不能取消引用结束列表迭代器
- 如何取消引用向量迭代器
- 在此C++代码中,迭代器引用列表的哪个元素?
- 使用双迭代器引用映射中的列表
- 使用自动迭代器引用对象
- 另一个迭代器引用的对象被另一个迭代器删除
- C++ 使用迭代器引用连续值
- 正确取消对指针的迭代器引用
- 如何在C++中存储对 stl 容器元素的指针/迭代器引用
- 具有代理迭代器/引用和auto的容器
- 返回迭代器引用C++
- 迭代器引用 std::vector<std::unique_ptr<T>>
- 迭代器引用受控序列中的元素的要求
- 什么是自动迭代器引用的 C++98 等效项?