Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Two dimensional unordered_map

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
like image 608
mikbal Avatar asked Dec 03 '25 19:12

mikbal


1 Answers

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:

typedef std::pair<int,int> Coordinates;
typedef std::unordered_map<Coordinates,void *> TwoDimensionalNodes;

(notice I used STL instead of Boost, unordered_map is now also part of the standard STL).

Getting a specific value is simply writing:

twoDimensionalNodes[std::make_pair(x,y)]

(or use find if you're not sure if that value is in your map).

To iterate, just iterate over the unordered map:

for (auto it=twoDimensionalNodes.begin();it!=twoDimensionalNodes.end();++it)
   {
   std::cout << "x=" << it->first.first;
   std::cout << "y=" << it->first.second;
   std::cout << "value=" << it->second;
   }

To make it a bit more readable, I prefer getting the coordinates first from the iterator, like this:

for (auto it=twoDimensionalNodes.begin();it!=twoDimensionalNodes.end();++it)
   {
   Coordinates &coordinates = it->first;
   std::cout << "x=" << coordinates.first;
   std::cout << "y=" << coordinates.second;
   std::cout << "value=" << it->second;
   }

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.

like image 73
Patrick Avatar answered Dec 05 '25 09:12

Patrick



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!