Vectors: rend () is invalidated by erasing ()

According to the C ++ specification (23.2.4.3), vector :: erase () only invalidates "all iterators and references after the erase point"

Thus, when using reverse_iterators to transmit all elements of a vector, erasing on the current iterator should not invalidate the rend () member.

This code will work under g ++, but will throw a run-time exception on Windows (VS2010):

#include <vector>

using namespace std;

int main()
{
    vector<int> x;
    x.push_back(1);
    x.push_back(2);
    x.push_back(3);

    //Print
    for(vector<int>::const_iterator i = x.begin(); i != x.end(); ++i)
        printf("%d\n", *i);

    //Delete second node
    for(vector<int>::reverse_iterator r = x.rbegin(); r != x.rend(); ++r)
        if(*r == 2)
            x.erase((r+1).base());

    //Print
    for(vector<int>::const_iterator i = x.begin(); i != x.end(); ++i)
        printf("%d\n", *i);

    return 0;
}

The error is interesting:

Expression: vector iterator does not decrease

Indicated on the line of the second cycle for the second run. The decrease refers to the internal “current” member of the iterator iterator iterator, which decreases each time the iterator is incremented.

Can someone explain this behavior please?

Thank.

EDIT

, , r, rend():

//Delete second node
for(vector<int>::reverse_iterator r = x.rbegin(); r != x.rend();)
{
    vector<int>::reverse_iterator temp = r++;

    if(*temp == 2)
        x.erase((temp+1).base());
}

vector iterators incompatible for .

+5
5

Undefined . .

std::vector<int>::reverse_iterator typedef std::reverse_iterator<std::vector<int>::iterator>. std::reverse_iterator<Iter> , protected Iter current;, reverse_iterator current.

, , r == reverse_iterator(i), i - std::vector<int> x;. .

r.current == i
(r+1).current == (i-1)
(r+1).base() == (i-1)

x.erase((r+1).base()); i-1 . , i, , r.current.

, , - ++r. --r.current;. r.current , Undefined Behavior; ++r.

+4

A reverse_iterator , , , . , rbegin , , .

+3

, :

struct CustomRemove
{
    bool operator()(int i)
    {
        return (i == 2);
    }
};

int main()
{
    std::vector<int> x;
    x.push_back(1);
    x.push_back(2);
    x.push_back(3);

    CustomRemove custom_remove;

    std::copy(x.begin(), x.end(), std::ostream_iterator<int>(std::cout, "\n"));
    x.erase(std::remove_if(x.begin(), x.end(), custom_remove), x.end());
    std::copy(x.begin(), x.end(), std::ostream_iterator<int>(std::cout, "\n"));

    return 0;
}
+2

_ . , rend() - begin(), . , base().

+1

(r+1).base() r , (r+1).base() r. , g++ , , .

, remove remove_if.

0

All Articles