Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to use stl::map as two dimension array

Tags:

c++

stl

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?

like image 810
user243655 Avatar asked Aug 03 '10 02:08

user243655


People also ask

How do you create a two dimension array?

Two dimensional array: int[][] twoD_arr = new int[10][20]; Three dimensional array: int[][][] threeD_arr = new int[10][20][30]; Size of multidimensional arrays: The total number of elements that can be stored in a multidimensional array can be calculated by multiplying the size of all the dimensions.

Can object be two-dimensional array?

Often data come naturally in the form of a table, e.g., spreadsheet, which need a two-dimensional array. Two-dimensional (2D) arrays are indexed by two subscripts, one for the row and one for the column. Each element in the 2D array must by the same type, either a primitive type or object type.

What is the use of map in STL?

Maps are associative containers that store elements in a mapped fashion. Each element has a key value and a mapped value. No two mapped values can have the same key values.


2 Answers

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]".

like image 151
Andrew Stein Avatar answered Oct 19 '22 00:10

Andrew Stein


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.

like image 39
Carlos Scheidegger Avatar answered Oct 18 '22 23:10

Carlos Scheidegger