tags:

views:

1086

answers:

4

Maps are great to get things done easily, but they are memory hogs and suffer from caching issues. And when you have a map in a critical loop that can be bad.

So I was wondering if anyone can recommend another container that has the same API but uses lets say a vector or hash implementation instead of a tree implementation. My goal here is to swap the containers and not have to rewrite all the user code that relies on the map.

Update: performance wise the best solution would be a tested map facade on a std::vector

+3  A: 

See Loki::AssocVector and/or hash_map (most of STL implementations have this one).

yrp
This is basically a sorted std::vector<std::pair<Key, T> > with map-like interface. The license is permissive enough to rip it out and stick into your project somewhere.
Greg Rogers
Sorry I hadn't came back to check the answer till now, but this is exactly what I needed! Thanks a perfect drop-in (considering the use cases I have)
Robert Gould
+1  A: 

If your key is a simple type that can be very quickly compared and you have no more than a few thousands of entries, you could have better performance by simply putting your pairs in an std::vector and iterating to find your value.

Carl Seleborg
Ideally that would be the best solution, but I don't want to write up (and debug) the vector's interface/wrapper to be Map compatible. Do you know of any implementation of this technique?
Robert Gould
Unfortunately not.
Carl Seleborg
+10  A: 

You can use std::tr1::unordered_map, which is already present in most STL implementations, and is part of the C++0x standard.

Here is it's current signature :

template <class Key,
          class T,
          class Hash = std::tr1::hash<Key>,
          class Pred = std::equal_to<Key>,
          class Alloc = std::allocator<std::pair<const Key, T> > >
class unordered_map;
Luc Touraille
I haven't used std::tr1::unordered_map, but if it's anything like STLport's hash_map, I wouldn't be surprised if a typical implementation is an even bigger memory hog than std::map and has equally bad spatial locality.
bk1e
+5  A: 

Maybe Google SparseHash could help you?

Igor Semenov