mrg95
mrg95

Reputation: 2418

How to make a 2D map similar to a 2D array

Is it possible to make a 2d map?

Like this:

map< int, int, string> testMap;

And filling the values would be like:

testMap[1][3] = "Hello";

Upvotes: 3

Views: 30651

Answers (3)

andre
andre

Reputation: 7249

yes, use std::pair within a std::map,

std::map< std::pair<int, int>, string> testMap;
testMap[std::make_pair(1,3)] = "Hello";

Upvotes: 26

Paul Nickerson
Paul Nickerson

Reputation: 31

In case it's helpful for anybody, here is code for a class that builds upon andre's answer, which allows access via bracket operators like a regular 2D array would:

template<typename T>
class Graph {
/*
    Generic Graph ADT that uses a map for large, sparse graphs which can be
    accessed like an arbitrarily-sized 2d array in logarithmic time.
*/
private:
    typedef std::map<std::pair<size_t, size_t>, T> graph_type;
    graph_type graph;
    class SrcVertex {
    private:
        graph_type& graph;
        size_t vert_src;
    public:
        SrcVertex(graph_type& graph): graph(graph) {}
        T& operator[](size_t vert_dst) {
            return graph[std::make_pair(vert_src, vert_dst)];
        }
        void set_vert_src(size_t vert_src) {
            this->vert_src = vert_src;
        }
    } src_vertex_proxy;
public:
    Graph(): src_vertex_proxy(graph) {}
    SrcVertex& operator[](size_t vert_src) {
        src_vertex_proxy.set_vert_src(vert_src);
        return src_vertex_proxy;
    }
};

Upvotes: 2

user2530166
user2530166

Reputation:

You can nest two maps:

#include <iostream>
#include <map>
#include <string>

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

    m[1][3] = "Hello";

    std::cout << m[1][3] << std::endl;

    return 0;
}

Upvotes: 15

Related Questions