24
  1. I know I can use *s.begin(), but same argument can be used for vector, which has front/back
  2. often I use the ordered property of set/map to get "smallest" element/key - ofc the fact that I do it is not the reason to have it, just a example :)

Here I'm talking about design reasons why front/back would be bad design, so please skip obvious reasons like committee forgot about it...

Enlico
  • 23,259
  • 6
  • 48
  • 102
NoSenseEtAl
  • 28,205
  • 28
  • 128
  • 277

1 Answers1

30

I imagine that the words "front" and "back" are reserved for sequence containers (i.e. those where the order of elements is determined by the order of insertion), and the words are meant to suggest a physical position in that sequence.

Since set is not a sequence container (but instead an associative container), this isn't appropriate. In particular, note that the meaning of "front" can change by later insertions of an unrelated element.

Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
  • 7
    The second paragraph doesn't really make sense; the `back` of a `vector` can change too, by a `push_back`. But +1 for the first paragraph. – Fred Foo May 21 '13 at 08:26
  • 8
    @larsmans: Yes, "back" can change if you change the back. But you'll be explicitly changing the back. In a set, it would be an *unrelated* change, if you see what I mean. This explanation works best when you think about a list. – Kerrek SB May 21 '13 at 08:27
  • (If you will, `std::list` is the star example, and `std::vector` has the exception that insertions invalidate "back", and `std::deque` has the exception that insertions in the middle invalidate both "front" and "back". Those statements are actually true on the nose for references.) – Kerrek SB May 21 '13 at 08:37
  • Of course, references need not be invalidated by unrelated updates (if I recall correctly that B-trees cannot be used for `std::set` because of invalidation issues), they just wouldn't point to the front or back any more. – Fred Foo May 21 '13 at 08:40
  • @larsmans: Indeed, in the standard library, all *node-based* containers retain full iterator and reference validity during arbitrary insertions and deletions. – Kerrek SB May 21 '13 at 08:41
  • Maybe it would make sense for these associative containers to have `first`/`last` (they would imply "... according to the provided or defaulted `Compare`"); or maybe `min`/`max`, despite the latter naming would be very confusing when the ordering predicate is chosen to be `std::greater`-like. – Enlico Mar 13 '22 at 13:45
  • If it's not meant to be a sequence, explain why we have `begin`/`end`. – Aykhan Hagverdili Feb 09 '23 at 09:49