问题描述
typedef boost::unordered_map<int, void*> OneDimentionalNodes;
typedef boost::unordered_map<int, OneDimentionalNodes> TwoDimentionalNodes;
TwoDimentionalNodes nodes;
这有效吗?
我不使用任何散列函数,因为 unordered_maps 的键是单个整数.它可以编译,但是当我像这样迭代它时,它在尝试访问 this->hash_function()(k); 时崩溃了;
i don't use any hash functions since keys of the unordered_maps' are single integers.it compiles, but when i iterate it like this, it crashes while trying to access this->hash_function()(k);
for (TwoDimentionalNodes::iterator it= nodes.begin(); it != nodes.end() ; ++it)
{
for(OneDimentionalNodes::iterator it2 = nodes[it->first].begin(); it2 != nodes[it->first].end() ; ++it2)
{
// do stuff
}
}
我也对其他容器开放
- O(1) 访问
- O(n) 迭代
- 稀疏
推荐答案
如果你只需要遍历所有元素,而不需要遍历特定维度,那么你可以使用一个简单的pair作为你的keyunordered_map,像这样:
If you just need to iterator over all elements, and it is not required to loop over a specific dimension, then you could use a simple pair as key for your unordered_map, like this:
typedef std::pair<int,int> Coordinates;
typedef std::unordered_map<Coordinates,void *> TwoDimensionalNodes;
(注意我使用了 STL 而不是 Boost,unordered_map 现在也是标准 STL 的一部分).
(notice I used STL instead of Boost, unordered_map is now also part of the standard STL).
获取一个特定的值很简单:
Getting a specific value is simply writing:
twoDimensionalNodes[std::make_pair(x,y)]
(或者,如果您不确定该值是否在您的地图中,请使用 find).
(or use find if you're not sure if that value is in your map).
要迭代,只需迭代无序映射:
To iterate, just iterate over the unordered map:
for (auto it=twoDimensionalNodes.begin();it!=twoDimensionalNodes.end();++it)
{
std::cout << "x=" << it->first.first;
std::cout << "y=" << it->first.second;
std::cout << "value=" << it->second;
}
为了让它更具可读性,我更喜欢先从迭代器中获取坐标,如下所示:
To make it a bit more readable, I prefer getting the coordinates first from the iterator, like this:
for (auto it=twoDimensionalNodes.begin();it!=twoDimensionalNodes.end();++it)
{
Coordinates &coordinates = it->first;
std::cout << "x=" << coordinates.first;
std::cout << "y=" << coordinates.second;
std::cout << "value=" << it->second;
}
如果您有超过 2 个维度,请使用 std::tuple,或者只需编写您自己的 Coordinates 类以用作地图的键.
If you have more than 2 dimensions, use std::tuple, or simply write your own Coordinates class to be used as key for the map.
这篇关于二维 unordered_map的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!