Search code examples
c++dictionarymultidimensional-arrayinitializationis-empty

Initialising a 2d map c++


I have been thinking lately about 2d structures (of integers) in which their sizes can grow dynamically. I came across 'map' which I think that it meets my following need: Essentially, what I want is to check whether a random entry has been initialized or not (do something if it has not been initialized yet).

int main(){ 
   int int1, int2;
   std::map<int,std::map<int,int>> my_map;
   cout << "Enter two integers separated by space: ";
   cin >> int1 >> int2;
   if(has my_map[int1][int2] not been initialized){
      do something
   }
}

I am hoping that such functionality is available with C++.


Solution

  • If what you mean by checking whether an entry "has been initialized" is checking that a pair of keys has a value assigned to them -- one key for the outer map and one for the inner map -- you can test contents of a map of maps as below:

    bool contains_keys(const std::map<int, std::map<int, int>>& map_of_maps, int key1, int key2) {
        auto iter = map_of_maps.find(key1);
        if (iter == map_of_maps.end()) {
            return false;
        }
        return iter->second.find(key2) != iter->second.end();
    }
    

    However, I question whether a map of maps is really what you want. If what you want is just a mapping from two keys to a single value, a more direct and space efficient implementation is to use an std::map with an std::tuple or std::pair as the key type.

    Tuples version below.

    #include <map>
    #include <tuple>
    #include <iostream>
    
    int main()
    {
        std::map<std::tuple<int, int>, int> map_of_pairs;
        map_of_pairs[{42, 17}] = 3;
    
        bool contains_42_17 = (map_of_pairs.find({ 42, 17 }) != map_of_pairs.end());
        bool contains_67_23 = (map_of_pairs.find({ 67, 23 }) != map_of_pairs.end());
    
        std::cout << ((contains_42_17) ? "yes\n" : "no\n");
        std::cout << ((contains_67_23) ? "yes\n" : "no\n");
    }
    

    Also unless you actually need the above to be ordered, consider an unordered_map.