Vocaloidas
Vocaloidas

Reputation: 370

Vector Iterator not dereferencable (trying to manually reverse vector)

I'm trying to create a function which takes in a vector and simply reverses (manually). I'm aware of the existence of reverse(), but I ran into the "Vector iterator not dereferencable" problem and for educational purposes, I'd like to know what it means. I tried researching this problem and someone (on this forum) said that vect.end() is not dereferencable by definition, but from my understanding, using reverse_iterator is just reversing the ends, so following the logic; vect.rend should not be dereferencable.

vector<int> reverseVector(vector<int>);

int main()
{
    vector<int> vec;

    for (int i = 0; i < 11; i++)
    {
        vec.push_back(i);
    }

    vec = reverseVector(vec);

    for (vector<int>::iterator it = vec.begin(); it != vec.end(); it++)
    {
        cout << *it << " ";
    }
    cout << endl;

    return 0;
}

vector<int> reverseVector(vector<int> vect) 
{
    vector<int>::reverse_iterator ritr;
    for (ritr = vect.rbegin(); ritr != vect.rend(); ritr++)
    {
        vect.insert(vect.begin(), *ritr);
        vect.pop_back();
    }
    return vect;
}

Upvotes: 1

Views: 202

Answers (5)

jsn
jsn

Reputation: 81

A tip as design-issue: use always const-reference in a function, unless you really know what you are doing. So you will avoid stepping in traps like this. For example:

vector<int> reverseVector(const vector<int> &vect)

Now you wont have this problem, because you can not modify vect.

Upvotes: 1

gsamaras
gsamaras

Reputation: 73414

You are deleting elements from the vector (popping from the back), which invalidates the reverse iterator.


You could just iterate through half of the vector and swap the elements, lke this:

void swap(int& a, int& b) {
    int tmp = a;
    a = b;
    b = tmp;
}

vector<int> reverseVector(vector<int> vect) {
    const size_t origin_size = vect.size();
    for(size_t i = 0; i < origin_size/2; ++i)
        swap(vect[i], vect[origin_size - 1 - i]);
    return vect;
}

Upvotes: 1

Ron
Ron

Reputation: 15521

Both insert and pop_back member functions modify the vector and invalidate iterators.

Upvotes: 1

wrangler
wrangler

Reputation: 3576

If you add an element to the vector, ritr may be invalidated thus the error

Vector iterator not dereferencable.

Thus its better using an index as your loop variable or better a copy(temp) vector for reverse task.

Upvotes: 1

user325117
user325117

Reputation:

Your problem has nothing to do with the dereferencability or otherwise of rend(). You're modifying the vector while iterating over it, which invalidates the iterator.

To answer your original question, a reverse_iterator isn't just "reversing the ends" compared to a forward iterator. rbegin() is end() - 1, and rend() is begin() - 1.

Upvotes: 1

Related Questions