使用无序映射在STL中存储键值对
Using unordered_map to store key-value pairs in STL
我必须在程序中存储一些数据,如下所述。
数据是高维坐标和这些坐标中的点数。以下是一个简单的例子(坐标尺寸为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
需要知道如何散列您的坐标。此外,它还需要一种方法来比较相等的坐标。
您可以将坐标包裹在class
或struct
中,并提供自定义运算符==来比较坐标点。然后,您需要专门处理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;
相关文章:
- 在C++中共享键值对的最佳方式
- 使用无序映射在STL中存储键值对
- c++同一个键的多个键/值对
- C++中的键值对:<val1, val2> 键<frequency>与值一样
- 在 std::unordered_map 中插入新的键/值对会导致"out of range"异常
- 读取数组中每个对象的所有键值对
- 这C++ unordered_map怎么有四个值?我以为这是一个键值对
- 使用 k 个键值对为零的存储桶初始化 c++14 unordered_map
- 从配置文件qsetting中删除键/值对
- 如何使用卡萨布兰卡在现有的web::json::value对象中附加新的键值对?
- 是否可以创建字符串和原子<int>键值对的unordered_map?
- 检索16k键值对的最快方法
- 按文件夹名称存储键值
- 将键值对文件读入 std::map
- 为什么用Spirit解析一个空行会在映射中产生一个空的键值对
- 从unordered_map C++中删除键/值对
- 如何在不使用任何DBMS的情况下将键值对数据存储在程序中
- 如何调整无序STL容器以仅存储键值对的值
- 在文件中存储由分隔符分隔的大量整数的键值对的最有效方法
- 从字符串中获取键/值对并存储在map中