C++ stl :: map find with structs

Jan*_*Jan 0 c++ map

我有结构存储有关ARP数据包的信息,我需要保存ARP请求并一起回复数据包.我想使用std :: map为此,键和映射值是ARP结构,我将使用find运算符来计算带有请求的回复.

我的问题是如何说map :: find只比较struct中的一些成员.

我想要描述的例子

struct arp_packet : public packet_info
{
    u_short type;   // 0x0001 request
                    // 0x0002 reply

    struct ipv4_address ip_sender;
    struct ipv4_address ip_target;
};
Run Code Online (Sandbox Code Playgroud)

我会像这样在地图中保存所有请求

std::map<arp_packet*, arp_packet*>
Run Code Online (Sandbox Code Playgroud)

首先映射的值为NULL,但是当回复数据包到来时,我将使用find方法将其与请求匹配.

那么我应该如何完成地图将arp_packet*作为关键字,并在发现它将采用另一个arp_packet*并使用ip_sender和ip_target匹配它?

Mat*_* M. 7

A std::map最多接受4个模板参数(最后2个具有默认值).

你将在这里使用第三个参数:一个用于比较两个键的仿函数.

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;
Run Code Online (Sandbox Code Playgroud)

注意实现正确的operator()语义,它应该与数学属性相匹配<,特别是反对称性传递性.