C ++ 2d地图?像二维阵列?

时间:2013-07-14 19:26:58

标签: c++ arrays map 2d

是否可以制作2d地图?

像这样:

map< int, int, string> testMap;

填写值将是:

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

感谢您的时间:)

3 个答案:

答案 0 :(得分:17)

是的,请使用std::pair

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

答案 1 :(得分:12)

您可以嵌套两张地图:

#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 :(得分:2)

如果它对任何人都有帮助,这里是一个基于andre的答案的类的代码,允许通过括号运算符访问,如常规2D数组:

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