使用带有结构的映射作为键 - 值不保存

Using map with structure as key - value doesn't save

本文关键字:保存 映射 结构      更新时间:2023-10-16

我对C ++ std::map容器和结构作为键几乎没有问题。

我想使用地图作为ipv6查找表的快速查找表。我有包含 IP 地址的文件,我想聚合它们。

我的地图键是

struct myipv6{
uint64_t MSB;
uint64_t LSB;
bool operator==(const myipv6 &a){
            return (MSB == a.MSB && LSB == a.LSB);
}
bool operator<(const myipv6 &a){
                return (MSB < a.MSB && LSB < a.LSB);
}
myipv6(){}
myipv6(const uint64_t A,const uint64_t B) :
    MSB(A),LSB(B) {}
};
bool operator < (const myipv6 &l, const myipv6 &r) { return ( l.MSB < r.MSB && l.LSB < r.LSB); }

数据从in6_addr插入

memcpy(&(ip), &src_addr, sizeof(myipv6));

这个建设工作,我尝试将数据复制到IP。从 ip 使用 memcpy 到另一个in6_addr并使用inet_pton来检查值是否正确。

地图声明为

map<myipv6, int> aggregate;
map<myipv6, int>::iterator it;

当我遍历文件中的所有 IP 地址并将其用于聚合时:

    it = aggregate.find(ip);
    if(!(ip == it->second.ip)){
            aggregate[ip] = 1;
    }else{
            it->second += 1;
    }

我得到不好的结果,记录丢失了...当我使用它时 == aggregate.end() 而不是 !(ip == it->second.ip) 对于 else 语句中的条件,我得到 it->First 不等于 IP。但是当我使用!(IP == it->second.ip) 迭代器具有任何值,当我将"新"项写入映射时,我会重写保存的数据。

这种奇怪的行为有什么不同吗?

最后一个问题,是否可以使用unordered_map而不是地图?

谢谢

你应该使用:

bool operator < (const myipv6 &l, const myipv6 &r) {
    return (l.MSB < r.MSB) || (l.MSB == r.MSB && l.LSB < r.LSB);
}

这称为词典顺序。

整个班级可能看起来像这样:

struct myipv6 {
    uint64_t MSB;
    uint64_t LSB;
    friend bool operator==(const myipv6 &a, const myipv6 &b) {
            return (a.MSB == b.MSB && a.LSB == b.LSB);
    }
    friend bool operator<(const myipv6 &a, const myipv6 &b) {
                return (a.MSB < b.MSB) || (a.MSB == b.MSB && a.LSB < b.LSB);
    }
    myipv6() {}
    myipv6(const uint64_t A,const uint64_t B) : MSB(A),LSB(B) {}
};

使用 friend 是定义这些比较运算符的一种优雅方法。