Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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).

like image 911
SylvainD Avatar asked Jun 07 '13 10:06

SylvainD


People also ask

What is the difference between map and multimap associative containers?

The map and the multimap are both containers that manage key/value pairs as single components. The essential difference between the two is that in a map the keys must be unique, while a multimap permits duplicate keys.

What is associative container explain any two associative containers with their functions?

In computing, associative containers refer to a group of class templates in the standard library of the C++ programming language that implement ordered associative arrays. Being templates, they can be used to store arbitrary elements, such as integers or custom classes.

Is map an associative container?

Maps are associative containers that store elements in a mapped fashion. Each element has a key value and a mapped value. No two mapped values can have the same key values.


2 Answers

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.

like image 59
Edward Strange Avatar answered Sep 19 '22 18:09

Edward Strange


Front() implies an ordering; "the first in the row".

Begin() implies lets start somewhere, no matter where.

like image 20
Enigma Avatar answered Sep 19 '22 18:09

Enigma