C++ key-value container with variable type values
What I need is a key-value container for keeping some well-known parameters of objects. All possible keys are known on compile time. Values are belong to differnt types: POD (integers, pointers) and non-POD (some small structures with contructors).
Current implementation uses very big structure and tons of code to initialize, fill and copy values. So I want to replace this structure with container. Container m开发者_如何学编程ust provide: 1) quick access by key (constant time). 2) the possibility to iterate over all values to copy them.
I tried to think up some array based approach, but coldn't make it. I can make some hash table, but I don't know what to do with different value types.
sounds like std::unordered_map
(or boost::unordered_map
) is the right solution. Just use boost::any
for the objects so they can be any type.
You might want to look at Boost.Variant for storing the values. Then you can just use a std::map<Key, boost::variant>
or std::unordered_map<Key, boost::variant>
for your container.
sounds like the std::map
is the right way to go.
While your keys are known at compile time, you may just populate the std::map structure with the data as part of the initialization.
For the value, you probably want to implement a wrapper objects which can hold int, pointers, and some of your simple-non-POD objects, and then make that your second (value) object in the std::hash table.
std::map, inplements .find(key)
for fast lookup and .begin()
and .end()
for ::iterator
's
You said:
All possible keys are known on compile time.
then you must be knowing the type as well.
If the type is integral type, then array or pointer of boost::any
is the best choice.
//if the size is known at compile time!
boost::any objmap[size];
//if the size isn't known at compile time
boost::any *objmap = new boost::any[size];
Whatever you use (array or pointer), the key will be the index of objmap
and objmap[key]
will be the value associated with the key.
精彩评论