is it possible to get index of object in map ? (linux, gcc)

  • Thread starter Maciej Kwapulinski
  • Start date
M

Maciej Kwapulinski

hallo.
This is my question:
let's assume a map like:

map< string, my_object > str_map;

map< string, my_object >::iterator iter = str_map.find("hallo");

map is an sorted container, so I think, question about index (ie. position
of objext in the map) of object 'iter' iterator points to, makes sense.

I was looking for a method to perform such operation but I didn't find any
:(((

Do You have any ideas ?

Thanks
Maciej
 
J

John Harrison

Maciej Kwapulinski said:
hallo.
This is my question:
let's assume a map like:

map< string, my_object > str_map;

map< string, my_object >::iterator iter = str_map.find("hallo");

map is an sorted container, so I think, question about index (ie. position
of objext in the map) of object 'iter' iterator points to, makes sense.

I was looking for a method to perform such operation but I didn't find any
:(((

Do You have any ideas ?

Thanks
Maciej

Use the distance function, which returns the distance from one iterator to
another (more or less).

map< string, my_object > str_map;
map< string, my_object >::iterator iter = str_map.find("hallo");

size_t index = std::distance(str_map.begin(), iter);

This isn't built into map because its not efficient. For a map iterator the
time taken to compute distance will be proportional to the value of the
index, i.e. it will take a lot longer to get your index for items near the
end of the map.

john
 
T

tom_usenet

hallo.
This is my question:
let's assume a map like:

map< string, my_object > str_map;

map< string, my_object >::iterator iter = str_map.find("hallo");

map is an sorted container, so I think, question about index (ie. position
of objext in the map) of object 'iter' iterator points to, makes sense.

I was looking for a method to perform such operation but I didn't find any
:(((

Do You have any ideas ?

It isn't random access, so getting the "index" (position number) of an
element in a map is linear time, but here's the code (following on
from yours):

int index = std::distance(str_map.begin(), iter);

I can't think of any use for the index though. What are you trying to
do?

Tom
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,102
Messages
2,570,646
Members
47,247
Latest member
GabrieleL2

Latest Threads

Top