user243655
user243655

Reputation: 8595

how to use stl::map as two dimension array

Could you let us know how to use stl:map as two dimension array? I wanted to access the individual elements as like mymap[i][j] where I do not know beforehand what the value of i or j could be. Any better ideas to do the same thing in other way?

Upvotes: 5

Views: 21826

Answers (3)

Andrew Stein
Andrew Stein

Reputation: 13150

You can do

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

For example:

#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, followed by "My map contains a value for [9][2]".

Upvotes: 26

Carlos Scheidegger
Carlos Scheidegger

Reputation: 1966

An alternative solution to Andrew Stein's which plays nicer with the rest of 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, with this way you don't need to chain two calls to map::find to search for a single value.

Upvotes: 9

BenG
BenG

Reputation: 1312

Consider using a kd-tree instead. Each level of branching will compare the i an j values in turn. See http://en.wikipedia.org/wiki/Kd-tree.

Upvotes: 0

Related Questions