简体   繁体   English

C ++中的向量迭代器

[英]vector iterator in c++

I am attempting to use iterators to walk over a vector<char*> in c++. 我正在尝试使用迭代器在C ++中遍历vector<char*> I have built a dummy program that is supposed to start at the end, and step backward (toward the beginning, or rend() ) on a number >0, and forward (toward the end, or rbegin() ) on a number <0, and exit on 0. if the iterator has reached either of the ends and the user attempts to step further, it should repeat the element at that end and not move the iterator. 我已经建立一个应该在端部开始,和向后步骤(朝向开始,或虚设程序rend()上的数> 0,并转发(朝向端部,或rbegin()上的数)< 0,然后从0退出。如果迭代器已到达两端,并且用户尝试进一步执行操作,则应在该端重复该元素,并且不要移动迭代器。 My problem is that, rather than doing that, if the user tries to run over the end, I just get a segfault. 我的问题是,如果用户尝试运行到最后,而不是那样做,我只会遇到段错误。 here's my code: 这是我的代码:

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

Can anyone identify the problem? 谁能找出问题所在?

EDIT 编辑

I forgot that I made a minor change. 我忘了我做了些小改动。 my previous code did not populate tmp in the initializing for loop. 我以前的代码没有在初始化for循环中填充tmp that has been fixed 已经修复

The problem is that the rend iterator points one item past the (reversed) end of sequence. 问题是rend迭代器指向序列(反向)末尾的一项。 Dereferencing it causes a segfault: 取消引用它会导致段错误:

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

A minimal fix could be 一个最小的修复可能是

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

Since the goal, effectively, is to not use the past-the-end position, I'd recast the problem: it needs two iterators, one pointing to the first element in the desired range, and one pointing to the last one. 由于目标实际上是不使用过去的位置,因此我重述了这个问题:它需要两个迭代器,一个指向所需范围内的第一个元素,另一个指向最后一个。 Then the mechanics become easy: 然后,机制变得简单:

if (it != end)
    ++it;
cout << *it << endl;

Similarly, going the other direction: 同样,朝另一个方向:

if (it != begin)
    --it;
cout << *it << endl;

Where begin and end are defined like this: 起点和终点的定义如下:

typedef vector<char*>::reverse_iterator iter;
iter begin = vect.rbegin();
iter end = --vect.rend();  // assumes that vect is not empty

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM