如何制作类似于2D数组的2D地图

问题描述 投票:0回答:3

可以制作二维地图吗?

像这样:

map< int, int, string> testMap;

填充值就像:

testMap[1][3] = "Hello";
c++ arrays dictionary 2d
3个回答
25
投票

是的,在

std::pair
中使用
std::map

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

15
投票

您可以嵌套两个地图:

#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;
}

2
投票

如果它对任何人都有帮助,这里是一个基于安德烈答案的类的代码,它允许通过括号运算符进行访问,就像常规的二维数组一样:

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;
    }
};
© www.soinside.com 2019 - 2024. All rights reserved.