typedef boost::unordered_map<int, void*> OneDimentionalNodes;
typedef boost::unordered_map<int, OneDimentionalNodes> TwoDimentionalNodes;
TwoDimentionalNodes nodes;
is this valid?
i don’t use any hash functions since keys of the unordered_maps’ are single integers.
it compiles, but when i iterate it like this, it crashes while trying to access this->hash_function()(k);
for (TwoDimentionalNodes::iterator it= nodes.begin(); it != nodes.end() ; ++it)
{
for(OneDimentionalNodes::iterator it2 = nodes[it->first].begin(); it2 != nodes[it->first].end() ; ++it2)
{
// do stuff
}
}
i’m also open to other containers with
- O(1) access
- O(n) iteration
- Sparse
If you just need to iterator over all elements, and it is not required to loop over a specific dimension, then you could use a simple pair as key for your unordered_map, like this:
(notice I used STL instead of Boost, unordered_map is now also part of the standard STL).
Getting a specific value is simply writing:
(or use find if you’re not sure if that value is in your map).
To iterate, just iterate over the unordered map:
To make it a bit more readable, I prefer getting the coordinates first from the iterator, like this:
If you have more than 2 dimensions, use std::tuple, or simply write your own Coordinates class to be used as key for the map.