使用无序映射在STL中存储键值对

Using unordered_map to store key-value pairs in STL

本文关键字:存储 键值对 STL 无序 映射      更新时间:2023-10-16

我必须在程序中存储一些数据,如下所述。

数据是高维坐标和这些坐标中的点数。以下是一个简单的例子(坐标尺寸为5(:

coordinate        # of points
(3, 5, 3, 5, 7)          6
(6, 8, 5, 8, 9)          4
(4, 8, 6, 7, 9)          3

请注意,即使我以5个维度为例,实际问题也是20个维度。坐标总是整数。

我想把这些信息存储在某种数据结构中。我首先想到的是一个哈希表。我在STL中尝试了unordered_map。但在CCD_ 2中却不知道如何使用坐标作为关键。定义为:

unordered_map<int[5], int> umap;

或者,

unordered_map<int[], int> umap;

给我一个编译错误。我做错了什么?

unordered_map需要知道如何散列您的坐标。此外,它还需要一种方法来比较相等的坐标。

您可以将坐标包裹在classstruct中,并提供自定义运算符==来比较坐标点。然后,您需要专门处理std::hash,以便能够将Point结构用作unordered_map中的键。虽然比较坐标是否相等相当简单,但如何对坐标进行哈希处理取决于您。以下是您需要实现的内容的概述:

#include <vector>
#include <unordered_map>
#include <cmath>
class Point
{
std::vector<int> coordinates;
public:
inline bool operator == (const std::vector<int>& _other)
{
if (coordinates.size() != _other.size())
{
return false;
}
for (uint c = 0; c < coordinates.size(); ++c)
{
if (coordinates[c] != _other[c])
{
return false;
}
}
return true;
}
};
namespace std
{
template<>
struct hash<Point>
{
std::size_t operator() (const Point& _point) const noexcept
{
std::size_t hash;
// See https://www.boost.org/doc/libs/1_67_0/doc/html/hash/reference.html#boost.hash_combine
// for an example of hash implementation for std::vector.
// Using Boost just for this might be an overkill - you could use just the hash_combine code here.
return hash;
}
};
}
int main()
{
std::unordered_map<Point, int> points;
// Use points...    
return 0;
}

如果你知道你要有多少坐标,你可以像这个一样命名

struct Point
{
int x1;
int x2;
int x3;
// ... 
}

你可以使用一个只有头的哈希库,我正是为了这个目的而写的。您的里程数可能有所不同。

破解方式

我在编程比赛中看到过这一点,以便于使用。您可以将点集转换为字符串(将每个坐标连接起来,并用空格或任何其他特殊字符分隔(,然后使用unordered_map<string, int>

unordered_map<string, int> map; int p[5] = {3, 5, 3, 5, 7};
string point = to_string(p[0]) + " " + to_string(p[1]) + " " to_string(p[2]) + " " to_string(p[3]) + " " to_string(p[4]);
map[point] = 6;