C++ 相邻发现:矢量迭代器不可取消引用

C++ Adjacent Find: Vector iterator not dereferencable

本文关键字:迭代器 不可取 可取消 引用 发现 C++      更新时间:2023-10-16

我有一个包含以下元素的排序向量:

myVect = {-47, -2, -2, 19, 80, 80, 80}

我正在尝试使用 adjacent_find 算法在单独的行上定位和打印出每个范围的重复元素,如下所示:

-2

-2

80 80

80

能够让我的代码进行编译,并且它会产生正确的输出,除了我收到一个运行时错误,说"矢量迭代器不可取消引用"。

这是代码:

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; 
}