That is, if container
not empty, can I do it safely:
std::vector<int> container;
container.push_back( 0xFACE8D );
auto last = container.end() - 1;
and this:
EDIT: replace -1
with --
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
, .