能否制作一个二维地图?
像这样:
map< int, int, string> testMap;
填写这些值的方式如下:
testMap[1][3] = "Hello";
感谢您的时间 :)
能否制作一个二维地图?
像这样:
map< int, int, string> testMap;
填写这些值的方式如下:
testMap[1][3] = "Hello";
是的,在 std::map
中使用 std::pair
。
std::map< std::pair<int, int>, string> testMap;
testMap[std::make_pair(1,3)] = "Hello";
你可以嵌套两个地图:
#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;
}
如果有帮助的话,这里提供了一个基于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;
}
};
std::pair
不像添加一个额外的std::map
那么重。使用一个 map 嵌套另一个 map 进行查找的时间复杂度是O(Lg(n)*Lg(n))
,而仅使用一个 pair 只需要O(Lg(n))
的时间复杂度。 - andreO(lg(n)*lg(n))
,而是O(lg(n) + lg(n))
或简写为O(lg(n))
。第一个映射查找需要lg(n)
时间,第二个也需要lg(n)
时间。当然,这是假设“数组”是正方形的情况下。这可能应该被拆分为m
和n
,但它仍然可以以类似的方式简化。 - michaelgulak