Home > Net >  Is std::vector::end()[-1] a undefined behavior?
Is std::vector::end()[-1] a undefined behavior?

Time:09-19

std::vector v { 1, 2, 3, 4, };

The v.end()[-1] is able to access element 4.

For a longabout 2 years time, I use *(v.rbegin() 0)...

Will it cause any problems if I only use indexes ranged on [-static_cast<int>(v.size()), -1]?

CodePudding user response:

You are allowed to use the subscript operator on a LegacyRandomAccessIterator.

i[n]    convertible to reference    *(i   n)

where n is of type std::iterator_traits<It>::difference_type (which is signed).

So, as long as you stay within the valid bounds, it's fine.

int main() {
    std::vector v { 1, 2, 3, 4, };

    for(auto i = -static_cast<std::ptrdiff_t>(v.size()); i < 0;   i) {
        std::cout << v.end()[i] << '\n';
    }
}

The cast may overflow though.

CodePudding user response:

v.end()[-1] for a non-empty vector is fine and accesses the last element.

And yes you can extend this to indexes in the range [-static_cast<int>(v.size()), -1].

But in general my preference would be to use reverse iterators if you want to iterate backwards through a vector. That's what they are designed for.

CodePudding user response:

That's just a more confusing way of spelling:

v.back();

And if you want n-th element from the back, just do:

v[v.size() - n];

Everyone understands what this does unambiguously.

  •  Tags:  
  • c
  • Related