Reducing the end of an iterator

I read today about how for containers that support bidirectional iteration, this piece of code is valid:

Collection c(10, 10);
auto last = --c.end();
*last;

This made me wonder if I needed to send a pair of bidirectional iterators [beg, end) to an algorithm in STL defined by --end? If so, should the result be dereferenced?

t

void algo(T beg, T end){
    //...
    auto iter = --end;
    //...
    *iter;
} 
+6
source share
4 answers

If the algorithm requires a range specified by bidirectional iterators firstand last, then it --lastmust be valid under the same conditions ++firstas, namely, that the range is not empty. The range is empty if and only if first == last.

, --last , , *--last .

, , ( ). prev, copy_backward, move_backward, reverse, reverse_copy, stable_partition, inplace_merge, [prev|next]_permutation.

, , , .

, end() . , --x , x r . , , , int *foo();, , --foo() . , , , end() , operator--, -, . , .

, :

auto last = --c.end();

.

auto last = c.end();
--last;

r, l.

+6

. --c.end() . , , , , , . , undefined. , , , . std::vector, , typedef . ( , , undefined , . , , , .)

, , , . . , , , : operator-- , .

EDIT ( ):

, , , std::next std::prev ++ 11. , , , . :

prev( c.end() );

, , , , , .

+6

, . , , , .

Is it possible that --enddepends on end == beg.

+1
source

This is only required for algorithms that require bidirectional iterators.

0
source

All Articles