2

可以制作二维地图吗?

像这样:

map< int, int, string> testMap;

填充值就像:

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

谢谢你的时间 :)

4

3 回答 3

22

是的,std::pair在 a中使用std::map

std::map< std::pair<int, int>, string> testMap;
testMap[std::make_pair(1,3)] = "Hello";
于 2013-07-14T19:29:28.667 回答
13

您可以嵌套两个地图:

#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;
}
于 2013-07-14T19:29:32.240 回答
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;
    }
};
于 2014-12-09T01:57:28.083 回答