【发布时间】:2013-07-12 15:31:46
【问题描述】:
可以制作二维地图吗?
像这样:
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";
【讨论】:
std::pair 不像添加一个额外的std::map 那么重。地图地图的查找时间为O(Lg(n)*Lg(n)),而一对地图只需O(Lg(n))。
O(lg(n)*lg(n))。这是O(lg(n) + lg(n)),或者只是O(lg(n))。第一个地图查找采用lg(n),第二个也采用lg(n)。当然,这是假设一个方形“阵列”。这可能应该分解为m 和n,但它仍然以类似的方式简化。
你可以嵌套两张地图:
#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 的答案的类的代码,它允许像常规二维数组一样通过括号运算符进行访问:
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;
}
};
【讨论】: