Search code examples
c++dictionarystliteratorcontainer-data-type

Why no front() method on std::map (and other associative containers from the STL)?


The STL reference seems to make a conceptual difference between :

  • 'Sequence containers' (array vector deque forward_list list) on one hand
  • 'Associative containers' (set multiset map multimap unordered_set unordered_multiset unordered_map unordered_multimap) on the other hand.

Also, it seems like we have :

  • all containers implementing a begin() method returning an iterator pointing to the first element in the container.
  • only the sequence containers having a front() method returning a reference to the first element in the container.

My understanding is that the front() method could easily be defined in terms of the begin() method by just dereferencing its return value.

Thus, my question is : why isn't the front() method defined for all objects defining the begin() method ? (which should be every container really)

(I guess that from a semantic point of view, it doesn't make as much sense to get the first element from a map as it does for the first element from a vector but I was wondering if there was a more valid explanation).


Solution

  • You really have to ask the standards committee on that one (comp.lang.c++.std) but my guess is that yeah, it just doesn't make as much sense. Further there's not as much clarity as to what it would mean. Do you want the root, the pre-order first, post-order first, first you inserted...? With sequences it's quite clear: front is one side, back the other. Maps are trees.