Is it safe in C ++ to subtract from container.end ()?

That is, if containernot empty, can I do it safely:

std::vector<int> container;
container.push_back( 0xFACE8D );
auto last = container.end() - 1;

and this:

EDIT: replace -1with --here:

std::list<int> container;
container.insert( 0xFACE8D );
auto last = container.end();
--last;

and again for an arbitrary non-empty container?

EDIT: Let me clarify the question.

Sometimes completely wrong code behaves incorrectly. The question is, assuming the code above compiles, is something like that safe?

It should be safe for regular C-style arrays because the corresponding iterators are just pointers. But is it safe for more complex containers?

Suppose one implements a list with iterators like this:

class MyListIterator {
    MyListIterator *prev, *next;
    MyListIterator * operator--() { return prev; }
    ...
};

class MyList {
    MyListIterator *end() { return NULL; }
    ...
}; 

Then an attempt to decrement container::end(), even though it is perfectly legal syntactically, will cause segfault.

, stl , . , stl::list, .

+4
2

std::vector , , vector.

std::list . (++) (--), (+, -) (>, <). list.

std::advance . ++ 11 iter - 1 std::prev.

+7

++ , std::vector<T>::iterator - , , . , - +.

std::vector, std::list<T>::iterator - , -- ++.

+3

Source: https://habr.com/ru/post/1609865/


All Articles