如何对Mac密钥的集合进行排序

How to sort collection of mac key

本文关键字:集合 排序 密钥 Mac      更新时间:2023-10-16

我需要存储设备列表。每个设备都有唯一的 MAC 地址。我想使用 stl 映射存储它,mac 地址作为密钥。

我定义了结构:

struct MacBytes
{
char byte1;
char byte2;
char byte3;
char byte4;
char byte5;
char byte6;
bool operator <(const MacBytes& rhs) const
{
    //add implamention here
}
}

任何实现"运算符<"功能的建议(对于 stl map 是必需的(,而无需使用许多 if 语句。或者可以向另一个陈述提出建议。

不要使用具有一堆单独的char字段的结构,而是使用 std::array<char, 6> 。 这是一种更简单的表示数据的方法,std::array已经有了operator<,因此您无需编写自己的数据。

使用std::tie(或者可能考虑将MacBytes实现为直接包含std::tuple(:

operator <(const MacBytes& lhs, const MacBytes& rhs)
{
    return std::tie(lhs.byte1,lhs.byte2,lhs.byte3,lhs.byte4,lhs.byte5,lhs.byte6) <
           std::tie(rhs.byte1,rhs.byte2,rhs.byte3,rhs.byte4,rhs.byte5,rhs.byte6);
}