C++ 相邻发现:矢量迭代器不可取消引用
C++ Adjacent Find: Vector iterator not dereferencable
我有一个包含以下元素的排序向量:
myVect = {-47, -2, -2, 19, 80, 80, 80}
我正在尝试使用 adjacent_find 算法在单独的行上定位和打印出每个范围的重复元素,如下所示:
-2-2
80 8080
我能够让我的代码进行编译,并且它会产生正确的输出,除了我收到一个运行时错误,说"矢量迭代器不可取消引用"。
这是代码:
vector<int>::iterator vectIt = myVect.begin();
while (vectIt != myVect.end()) {
vectIt = adjacent_find(vectIt, myVect.end());
int currentVal = *vectIt;
while (*vectIt == currentVal) {
cout << *vectIt << " ";
if (vectIt < myVect.end()) {
++vectIt;
}
}
cout << endl;
}
有什么建议吗?
你在第二个循环中取消引用了end
迭代器。
while (*vectIt == currentVal) {
cout << *vectIt << " ";
if (vectIt < myVect.end()) {
++vectIt;
}
}
只需手动处理vectIt
是向量中最后一个元素的情况(即 myVect.end() - 1
,就像你在第 3 80
时得到的那样):
if (vectIt < myVect.end()) { // will still be true
++vectIt; // now you set it to myVect.end()
}
现在,在下一次迭代中,您检查:
while (*vectIt == currentVal) // here you dereference it without checking for myVect.end()
应将该条件更改为:
while (vectIt != myVect.end() && *vectIt == currentVal)
注意:仅当向量中的最后一个元素至少为 2 个相等的元素时,这才有效。如果向量中的最后一个元素不等于它之前的元素,就像{-47, -2, -2, 19, 80, 80, 80, 100}
那样,那么你只会在你的之后点击 myVect.end() vectIt = adjacent_find(vectIt, myVect.end());
如果vectIt
等于 myVect.end()
,要么会break
它之后,或者更确切地说,就像我建议的那样将更新放在 while 条件下。
vector<int>::iterator vectIt = myVect.begin();
while ( ( vectIt = adjacent_find(vectIt, myVect.end()) ) != myVect.end()) {
int currentVal = *vectIt;
while (vectIt != myVect.end() && *vectIt == currentVal) {
cout << *vectIt << " ";
if (vectIt < myVect.end()) {
++vectIt;
}
}
cout << endl;
}
相关文章:
- 为什么范围算法与 std 的迭代器不兼容?
- 矢量迭代器不能与 std::shared_ptr<> 取消引用
- forward_list迭代器不兼容
- 向量迭代器不兼容的错误,用于保存另一个向量的迭代器的向量
- C++,弹出调试断言失败窗口,我得到矢量迭代器不兼容的错误运行时
- f.getline() 迭代器不增加
- 当我发生碰撞检测时,矢量迭代器不兼容
- 为什么C++字符串迭代器不检查错误?
- debug断言矢量迭代器不可用find_if删除
- 为什么标准容器迭代器不会重载"->*"?
- 为什么反向迭代器不是 C++17 标准下的正式迭代器类别?
- C XTREE崩溃在出口上,映射/设置迭代器不可用
- C++:为什么输出迭代器不支持比较操作?
- 迭代器不兼容错误
- C++向量迭代器不是增量的
- 为什么更多的迭代器不是随机访问?
- 为什么迭代器不返回集合的开头
- 字符串迭代器不兼容错误,当我将字符串转换为矢量<byte>时
- 迭代器不能被另一个相同大小的向量重用吗?
- 字符串迭代器不可用C 问题