[英]C++ stl::map find with structs
I have struct that store info about ARP packet and I need to save the ARP request and reply packet together. 我有存储有关ARP数据包信息的结构,我需要一起保存ARP请求和答复数据包。 I would like to use std::map for this, the key and mapped value is that ARP struct, and I would be using the find operator to math the reply with request.
我想为此使用std :: map,键和映射的值是该ARP结构,并且我将使用find运算符对请求的答复进行数学运算。
My question is how can I say map::find to compare only some members from struct. 我的问题是如何说map :: find仅比较struct中的某些成员。
Example of what I'm trying to describe 我要描述的例子
struct arp_packet : public packet_info
{
u_short type; // 0x0001 request
// 0x0002 reply
struct ipv4_address ip_sender;
struct ipv4_address ip_target;
};
I would save all request in map like this 我会像这样将所有请求保存在地图中
std::map<arp_packet*, arp_packet*>
First the mapped value is NULL but whet the reply packet comes I will use the find method to match it to request. 首先,映射的值为NULL,但是当回复数据包到来时,我将使用find方法将其与请求匹配。
So how should I accomplist that the map would take as key the arp_packet *, and in find it would take the another arp_packet * and match it using ip_sender and ip_target? 因此,我应该如何兼顾地图将arp_packet *作为键,并找到另一个arp_packet *并使用ip_sender和ip_target进行匹配?
A std::map
accepts up to 4 template parameters (the last 2 have default values). 一个
std::map
最多接受4个模板参数(最后2个具有默认值)。
You would be using the 3rd parameter here: a functor meant to compare two keys. 您将在此处使用第3个参数:一个函子,用于比较两个键。
struct ArpComparator {
bool operator()(arp_packet* const left, arp_packet* const right) {
// compare the fields you need here
}
};
typedef std::map<arp_packet*, arp_packet*, ArpComparator> ArpMap;
Be careful about implementing a proper operator()
semantics, it should match the mathematical properties of <
, notably antisymmetry and transitivity . 在实现适当的
operator()
语义时要小心,它应该与<
的数学属性匹配,尤其是反对称性和可传递性 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.