Connecting Tech Pros Worldwide Forums | Help | Site Map

std::map observation

lallous
Guest
 
Posts: n/a
#1: Jul 22 '05
Hello,

I noticed that as I insert items to std::map<std::string, std::string> map1
as:
map1["test"] = "hello";
map1["hello"] = "test";

Then use an iterator to walk in the map, the items will be retrieved by the
alphabetical order of the keys...is there is a way to allow std::map to enum
items in the order of insertion?

--
Elias



Dimitris Kamenopoulos
Guest
 
Posts: n/a
#2: Jul 22 '05

re: std::map observation


lallous wrote:
[color=blue]
> Hello,
>
> I noticed that as I insert items to std::map<std::string, std::string>
> map1 as:
> map1["test"] = "hello";
> map1["hello"] = "test";
>
> Then use an iterator to walk in the map, the items will be retrieved by
> the alphabetical order of the keys...is there is a way to allow std::map
> to enum items in the order of insertion?[/color]

No. An std::map is a balanced tree that stays sorted whatever you put in it.
The insertion order is lost. Read any introductory text on trees. If you
want to enum items in the order of insertion you need a linear data
structure, such as a list or a deque.

Brian Genisio
Guest
 
Posts: n/a
#3: Jul 22 '05

re: std::map observation


lallous wrote:[color=blue]
> Hello,
>
> I noticed that as I insert items to std::map<std::string, std::string> map1
> as:
> map1["test"] = "hello";
> map1["hello"] = "test";
>
> Then use an iterator to walk in the map, the items will be retrieved by the
> alphabetical order of the keys...is there is a way to allow std::map to enum
> items in the order of insertion?
>
> --
> Elias
>
>[/color]

From the implementations of the map containers I have seen, the map is
stored in a red-black, ordered tree. This greatly increases the lookup
speed. Storing in input order is very slow, and would make most
instances of std::map useless to the programmer.

If you want something ordered in the order they were put in there, use a
vector or list of pairs, and do a scan of the container (for loop) for
the key.

Brian

Ron Natalie
Guest
 
Posts: n/a
#4: Jul 22 '05

re: std::map observation



"lallous" <lallous@lgwm.org> wrote in message news:bu3dt8$cp4m4$1@ID-161723.news.uni-berlin.de...[color=blue]
> Hello,
>
> I noticed that as I insert items to std::map<std::string, std::string> map1
> as:
> map1["test"] = "hello";
> map1["hello"] = "test";
>
> Then use an iterator to walk in the map, the items will be retrieved by the
> alphabetical order of the keys...is there is a way to allow std::map to enum
> items in the order of insertion?[/color]

The only ordering the std::map knows is the one specified in it's declaration
(by default the simple Less (operator<) ordering). You can't change it, it's
inherently how the map is arranged internally. The "insertion order" is not
remembered anywhere. If you need the insertion order, you'll have to remember
it elsewhere.

Closed Thread