c++ - 使用自定义比较器定义映射,其中值数据结构也具有自定义比较器
问题描述
我想定义一个数据结构,如:
struct node {
int x_coordinate;
int y_coordinate;
// some variables
};
map<node, priority_queue<node> > M;
// or lets say
map<node, set<node> > M
我面临的问题是我不知道如何编写它的自定义比较器
您还认为是否可以根据与关键节点的距离对priority_queue 进行排序。例如,假设我有 x_coordinate=0 和 y_coordinate=0 的关键节点,并且我想插入 (8,6),(4,3),(15, 9),(0,1)。
所以priority_queue类似于 (0,1) (4,3) (8,6) (15,9)
PS:在与人们讨论后,我使用了以下代码,但它仍然给出编译错误
struct Node {
Node (int a, int b) {
x = a;
y = b;
}
int x, y;
};
struct cmp {
Node node(0,0); // this node corresponds to the node that came from map key
cmp(Node node) {
this->node = node;
}
int getDistance (Node a, Node b) {
return abs(a.x - b.x) + abs(a.y - b.y);
}
bool operator () (Node node1, Node node2) {
return (getDistance(node, node1) < getDistance(node, node2));
}
};
int main() {
auto mapCmp = [&] (Node node1, Node node2){
return node1.x < node2.x and (node1.x == node2.x and node1.y < node2.y);
};
map<Node, priority_queue<Node, vector<Node>, cmp(Node)>, decltype(mapCmp)> myMap(mapCmp);
myMap[Node(0,0)].push(Node(2,4));
myMap[Node(0,0)].push(Node(1,3));
myMap[Node(0,1)].push(Node(2,4));
myMap[Node(0,1)].push(Node(1,3));
return 0;
}
错误快照:
解决方案
有趣的问题。后一部分(基于映射源键值的优先级顺序)提出了真正的挑战。
映射自定义键比较
从键比较到映射的基本三种方法是:
operator <
为映射键类型提供成员覆盖,或者- 提供一个仿函数类型作为映射的比较器,或者
- 提供免费功能。
其中最常见的是第一个,仅仅是因为它最容易实现和可视化。map 的默认比较器是std::less<K>
whereK
是 key 类型。标准库std::less
默认尝试operator <
比较,实际上它是这样做的:
bool isLess = (a < b)
wherea
和b
都是您的密钥类型。因此,一个简单的成员 constoperator <
重载将满足要求并为您提供所需的内容:
struct Node {
Node(int a=0, int b=0)
: x(a), y(b)
{
}
int x, y;
// called by default std::less
bool operator <(const Node& rhs) const
{
return (x < rhs.x) || (!(rhs.x < x) && y < rhs.y);
}
// simple distance calculation between two points in 2D space.
double distanceFrom(Node const& node) const
{
return std::sqrt(std::pow((x - node.x), 2.0) + std::pow((y - node.y), 2.0));
}
friend std::ostream& operator <<(std::ostream& os, Node const& node)
{
return os << '(' << node.x << ',' << node.y << ')';
}
};
这支持严格的弱顺序并且就足够了。其他选项有点复杂,但不是很多。我不会在这里介绍它们,但是有很多关于 SO 的问题。
注意:我在最终示例中添加了distanceFrom
and成员和朋友以供以后使用;operator <<
你稍后会看到他们。
优先队列实例比较覆盖
以前从未这样做过,但如果有更简单的方法,我当然愿意接受建议。为您的优先级队列使用模板类型的比较器覆盖的问题是您不能真正做到这一点。您希望根据到原点的距离对每个队列进行排序,其中原点是该队列的映射键。这意味着必须以某种方式为每个比较对象提供映射键的来源,而您不能使用模板类型覆盖(即编译时的东西)来做到这一点。
但是,您可以做的是提供实例比较覆盖。std::priority_queue
允许您在创建队列的位置提供自定义比较对象(在我们的例子中,当它作为映射到目标插入到地图中时)。稍微按摩一下,我们想出了这个:
首先,一个优先级函子,它不带参数或节点。
// instance-override type
struct NodePriority
{
NodePriority() = default;
NodePriority(Node node)
: key(std::move(node))
{
}
// compares distance to key of two nodes. We want these in
// reverse order because smaller means closer means higher priority.
bool operator()(const Node& lhs, const Node& rhs) const
{
return rhs.distanceFrom(key) < lhs.distanceFrom(key);
}
private:
Node key;
};
using NodeQueue = std::priority_queue<Node, std::deque<Node>, NodePriority>;
这using NodeQueue
将为我们节省大量输入下面的示例。
样本
使用上面的内容,我们现在已经准备好构建我们的地图和队列了。下面创建一个由十个节点组成的随机列表,每个节点的进位和 x,y 都在 1..9 的范围内。然后我们使用这些节点构建十个优先级队列,一个用于我们正在创建的每个映射条目。映射条目是对角线切片(即 (1,1)、(2,2)、(3,3) 等)。使用相同的十个随机元素,当我们报告最终结果时,我们应该会看到不同的优先级队列排序。
#include <iostream>
#include <vector>
#include <string>
#include <cstdlib>
#include <queue>
#include <map>
#include <random>
struct Node {
Node(int a=0, int b=0)
: x(a), y(b)
{
}
int x, y;
// called by default std::less
bool operator <(const Node& rhs) const
{
return (x < rhs.x) || (!(rhs.x < x) && y < rhs.y);
}
// simple distance calculation between two points in 2D space.
double distanceFrom(Node const& node) const
{
return std::sqrt(std::pow((x - node.x), 2.0) + std::pow((y - node.y), 2.0));
}
friend std::ostream& operator <<(std::ostream& os, Node const& node)
{
return os << '(' << node.x << ',' << node.y << ')';
}
};
// instance-override type
struct NodePriority: public std::less<Node>
{
NodePriority() = default;
NodePriority(Node node)
: key(std::move(node))
{
}
// compares distance to key of two nodes. We want these in
// reverse order because smaller means closer means higher priority.
bool operator()(const Node& lhs, const Node& rhs) const
{
return rhs.distanceFrom(key) < lhs.distanceFrom(key);
}
private:
Node key;
};
using NodeQueue = std::priority_queue<Node, std::deque<Node>, NodePriority>;
int main()
{
std::mt19937 rng{ 42 }; // replace with { std::random_device{}() } for random sequencing;
std::uniform_int_distribution<> dist(1, 9);
std::map<Node, NodeQueue> myMap;
// generate ten random points
std::vector<Node> pts;
for (int i = 0; i < 10; ++i)
pts.emplace_back(Node(dist(rng), dist(rng)));
for (int i = 0; i < 10; ++i)
{
Node node(i, i);
myMap.insert(std::make_pair(node, NodeQueue(NodePriority(node))));
for (auto const& pt : pts)
myMap[node].emplace(pt);
}
// enumerate the map of nodes and their kids
for (auto& pr : myMap)
{
std::cout << pr.first << " : {";
if (!pr.second.empty())
{
std::cout << pr.second.top();
pr.second.pop();
while (!pr.second.empty())
{
std::cout << ',' << pr.second.top();
pr.second.pop();
}
}
std::cout << "}\n";
}
}
注意:伪随机生成器总是播种42
以具有可重复的序列。当您决定通过不可重复测试来放松这一点时,只需将该种子替换为声明旁边的注释中提供的种子即可。
输出(当然,您的输出会有所不同)。
(0,0) : {(3,1),(5,1),(3,5),(5,3),(5,4),(5,5),(1,9),(6,7),(5,8),(6,8)}
(1,1) : {(3,1),(5,1),(3,5),(5,3),(5,4),(5,5),(6,7),(1,9),(5,8),(6,8)}
(2,2) : {(3,1),(3,5),(5,1),(5,3),(5,4),(5,5),(6,7),(5,8),(1,9),(6,8)}
(3,3) : {(3,1),(3,5),(5,3),(5,4),(5,5),(5,1),(6,7),(5,8),(6,8),(1,9)}
(4,4) : {(5,4),(5,5),(3,5),(5,3),(5,1),(3,1),(6,7),(5,8),(6,8),(1,9)}
(5,5) : {(5,5),(5,4),(3,5),(5,3),(6,7),(5,8),(6,8),(5,1),(3,1),(1,9)}
(6,6) : {(6,7),(5,5),(6,8),(5,4),(5,8),(3,5),(5,3),(5,1),(1,9),(3,1)}
(7,7) : {(6,7),(6,8),(5,8),(5,5),(5,4),(3,5),(5,3),(1,9),(5,1),(3,1)}
(8,8) : {(6,8),(6,7),(5,8),(5,5),(5,4),(3,5),(5,3),(1,9),(5,1),(3,1)}
(9,9) : {(6,8),(6,7),(5,8),(5,5),(5,4),(3,5),(5,3),(1,9),(5,1),(3,1)}
我会让你验证 distanceFrom 计算的准确性,但希望你明白这一点。
推荐阅读
- authentication - 如何修复团队基础网站上的错误 401.1
- reactjs - Redux 状态发生了奇怪的变化
- sql - 在表中显示值,即使查询返回无
- matlab - 一组子图的标题
- c - 为什么 gcc 打印“分段错误:11”?
- javascript - 检测点击外部组件
- c# - 使用 Entity Framework 的简单请求的大量执行时间
- odoo - odoo.tools.convert.ParseError:“在系统中找不到外部 ID:account.report_invoice_with_payments
- java - Mockito - 预期 0 个匹配器,记录 2 个(InvalidUseOfMatchersException)
- elasticsearch - Elasticsearch 连接器作为 Flink 中的源