c++ - C++中的 vector 迭代器

标签 c++ vector iterator segmentation-fault

我正在尝试使用迭代器遍历 vector<char*>在 C++ 中。我已经构建了一个虚拟程序,它应该从末尾开始,然后在 >0 的数字上后退(向开头,或 rend()),并在 < 0,并在 0 处退出。如果迭代器已到达任一端并且用户尝试进一步,它应该在该端重复该元素并且不移动迭代器。我的问题是,如果用户试图跑到最后,而不是这样做,我只会得到一个段错误。这是我的代码:

#include <iostream>
#include <vector>
#include <stdio.h>

using namespace std;

int main(){
    vector<char*> vect;
    char* tmp;
    for (int i=1; i<=5; i++){
        tmp = new char[7];
        sprintf(tmp, "hello%d", i);
        vect.push_back(tmp);
    }

    vector<char*>::const_reverse_iterator it = vect.rbegin();

    int a;
    cin >> a;

    while (a!=0){
        if (a>0){
            if (it < vect.rend()){
                cout << *(++it) << endl;
            } else{
                cout << *it << endl;
            }
        } else{
            if (it > vect.rbegin()){
               cout << *(--it) << endl;
            } else{
                cout << *it << endl;
            }
        }
        cin >> a;
    }

    return 0;
}

谁能找出问题所在?

编辑

我忘了我做了一个小改动。我以前的代码没有填充 rbegin()在初始化for循环中。已修复

最佳答案

问题在于 rend 迭代器将一项指向序列的(反向)末端。取消引用它会导致段错误:

    if (it < vect.rend()){
        cout << *(++it) << endl;
    } else{
        cout << *it << endl;    // <---- segfault
    }

一个最小的修复可能是

if (it+1 < vect.rend())
{
    cout << *(++it) << endl;
} else{
    cout << *it << endl;   
}

关于c++ - C++中的 vector 迭代器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11936754/

相关文章:

c++ - C++:实现Vector和Matrix类的最佳结构

c++ - ostream_iterator increment应该在什么情况下使用?

flutter - 迭代器当前为空,但为什么呢?

c++ - 下一个排列定义

c++ - 链表删除和复制

c++ - 将预编译的 HLSL 着色器加载到内存中以与 CreatePixelShader 一起使用

c++ - 使用 Eclipse 在 Windows 中为 Linux 编译 C++ 程序?

c++ - boost::ptr_vector 对比 std::vector<std::unique_ptr<T>>?

c++ - std::vector 每次使用时都填充相同的数据

python - itertools中chain和chain.from_iterable有什么区别?