Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a reason to use a mapping of string => index into a vector, instead of string => object?

If I have a collection of objects that I'd like to be able to look up by name, I could of course use a { string => object } map.

Is there ever a reason to use a vector of objects along with a { string => index into this vector } companion map, instead?

I've seen a number of developers do this over the years, and I've largely dismissed it as an indication that the developer is unfamiliar with maps, or is otherwise confused. But in recent days, I've started second-guessing myself, and I'm concerned I might be missing a potential optimization or something, though I can't for the life of me figure out what that could optimize.

like image 454
koschei Avatar asked Feb 10 '23 21:02

koschei


1 Answers

There is one reason I can think of:

Besides looking up object by name, sometimes you also want to iterate through all the objects as efficient as possible. Using a map + vector can achieve this. You pay a very small penalty for accessing the vector via index, but you could gain a big performance improvement by iterating a vector rather than a map (because vector is in continuous memory and more cache friendly).

Of course you can do similar thing using boost::multiindex, but that has some restrictions on the object itself.

like image 86
swang Avatar answered Feb 13 '23 20:02

swang