0

When a std::string is "" or a vector has no elements, is begin() equal to end()?

If so, what the value of begin()/end()?

templatetypedef
  • 362,284
  • 104
  • 897
  • 1,065
jiafu
  • 6,338
  • 12
  • 49
  • 73

2 Answers2

6

When a std::string is "" or a vector has no elements, is begin() equal to end()?

Yes, for any empty standard library container, including std::string and std::vector, begin() will return the same iterator as end().

If so, what the value of begin()/end()?

It will be an iterator which is unique to that container, but should not be dereferenced. Doing so would cause undefined behavior.

Drew Dormann
  • 59,987
  • 13
  • 123
  • 180
  • Why is it undefined instead of throwing an exception? efficiency? – Elazar May 13 '13 at 23:58
  • 2
    @Elazar, Because "you pay for what you need" is a common sight in C++. – chris May 13 '13 at 23:58
  • 1
    @Elezar exceptions aren't for programmer mistakes. – Pubby May 13 '13 at 23:58
  • thanks, chris @Pubby (it's "elazar" BTW). so conceptually it should have been an `assert`, except the library is tuned to release mode and hence doesn't have asserts in it. Am I right? Or are there other gotcha's here? – Elazar May 14 '13 at 00:09
  • @Elazar There are never `assert`s either. If you are iterating through any container it is the responsibility of *your code* to check whether you have reached the `end()` iterator. C++ will not check all your iterator dereferences to see if they're invalid. It's assumed that *you're* checking. – Drew Dormann May 14 '13 at 14:22
4

Yes. Any STL container type with no elements will have begin() == end(), as the range of elements is the half-open range [begin(), end()).

Hope this helps!

templatetypedef
  • 362,284
  • 104
  • 897
  • 1,065