Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Are map keys guaranteed to be in some specific order??

8 views
Skip to first unread message

Ramon F. Herrera

unread,
Apr 4, 2013, 1:11:52 PM4/4/13
to

I would be satisfied if I knew that keys are retrieved in the order
they were created.

-Ramon

nvangogh

unread,
Apr 4, 2013, 4:38:24 PM4/4/13
to
Well, I have not used this facility before so I am no expert on maps -
but I will try to help you today.

As you know a map is associative container type. A map can store it's
elements in order or not. If it is an un_ordered map then the keys will
not be in any particular order as a 'hash' function will be used instead.

A hash map does not seem to be what you are seeking.

A regular map must have an order placed on the keys:

"The map requires that a less-than operation exist for it's key types
and keeps its elements sorted so that iteration over a map occurs in
order." (Stroustrup C++ programming language 3rd edition p480)

Unfortunately, to see if there is a 'guarantee' about retrieval order
you would have to own a copy of the C++ standard. But it seems that this
is implied by the above quote.

Regards


scott

unread,
Apr 9, 2013, 8:04:46 AM4/9/13
to
On Thursday, April 4, 2013 7:11:52 PM UTC+2, Ramon F. Herrera wrote:
> I would be satisfied if I knew that keys are retrieved in the order
> they were created.

The "...were created" bit is misleading. std::map stores using a strict weak ordering on the keys. By default it uses operator< to determine where to place (I suppose in it's internal structure) an inserted element. You can also specify a Comparer as one of the template parameters. Among other things, this allows you to create a case insensitive string map, for example.

If you are using std::string, or int as the key, the ordering will be something like what you'd expect, from lowest to highest if you iterate over the map.

Scott
0 new messages