How to use stl :: map as an array of dimensions

Could you tell us how to use stl: map as two dimension arrays? I wanted to access individual elements like mymap [i] [j], where I do not know in advance what the value of i or j is. Any better ideas to do the same thing differently?

+4
source share
3 answers

You can do

std::map<int, std::map<int, int> > mymap;

For instance:

#include <map>
#include <iostream>

int main() 
{
    std::map<int, std::map<int, int> > mymap;

    mymap[9][2] = 7;
    std::cout << mymap[9][2] << std::endl;

    if (mymap.find(9) != mymap.end() && mymap[9].find(2) != mymap[9].end()) {
        std::cout << "My map contains a value for [9][2]" << std::endl;
    } else {
        std::cout << "My map does not contain a value for [9][2]" << std::endl;
    }

    return 0;
}

prints 7 on the standard output, and then "My card contains the value for [9] [2]."

+21
source

An alternative solution for Andrew Stein, which plays better with the rest of the STL, is to simply use

typedef std::map<std::pair<int, int>, int > AMapT;
AMapT mymap;
mymap[std::make_pair(2, 4)] = 10;
...
AMapT::iterator f = mymap.find(std::make_pair(3, 5));

For example, in this way you do not need to bind two calls map::findto find the same value.

+9

Use the kd tree instead. Each branch level will alternately compare the values ​​of i j. See http://en.wikipedia.org/wiki/Kd-tree .

0
source

All Articles