Is it safe to call iterative methods such as STL container erase (the override taking 2 iterators), e.g. in my case std::vector::erase()
, with both arguments being vec.end()
? I made an experiment and it looks like the call just does nothing, but I want to be sure I can use it safely in the code, otherwise I have to test my iterators and avoid erase()
if they're equal.
Asked
Active
Viewed 219 times
0

billz
- 44,644
- 9
- 83
- 100

cfa45ca55111016ee9269f0a52e771
- 2,153
- 3
- 26
- 39
-
@SethCarnegie Is it standard? I mean, can I fully rely on that, compiler-independent? cplusplus.com and cppreference.com don't explain this special case... – cfa45ca55111016ee9269f0a52e771 Feb 12 '13 at 02:08
-
2Yes, it's safe everywhere. It's not a special case; `erase` removes all elements in the range `[a, b)`, and if `a == b`, it removes no elements. – Seth Carnegie Feb 12 '13 at 02:10
-
@SethCarnegie general StackOverflow question, what do I do if I get the answer in comments? I can't mark the question as answered – cfa45ca55111016ee9269f0a52e771 Feb 12 '13 at 02:13
-
@Seth Technically, you were first to answer this, so if you want to, you can answer this and I'll delete mine. – us2012 Feb 12 '13 at 02:15
-
1Just make sure you use real iterators! The phrase 'invalid arguments' could cover a multitude of sins, most of which are NOT OK. – Michael Kohne Feb 12 '13 at 02:16
-
@us2012 He wasn't the first to answer, he was the first to comment. – David G Feb 12 '13 at 02:17
-
1@fr33domlover if someone answers in the comments then just take the knowledge and mark some other answer as the answer. Perhaps if they give some indication that they're going to write a real answer, you might want to wait for them and accept their answer if you feel like it, but I'm not going to write one (I generally only answer yes/no questions in comments). – Seth Carnegie Feb 12 '13 at 02:19
2 Answers
7
C++ Standard (n3337), 23.2.3, Sequence containers, Table 100 ('sequence container requirements) - row a.erase(q1,q2)
:
Effects: Erases the elements in the range
[q1,q2)
.
This means that a.erase(q,q)
is safe because it does nothing.
Loki Astari's answer to this SO question has a list of drafts of the C++ standard. The official copy is not freely available unfortunately, so I am using n3337, which seems to be the closest to C++11.
2
It is safe ; it is an effective no-op because end() -> end() is a range that is empty.

Richard Harrison
- 19,247
- 4
- 40
- 67