使用带有结构的映射作为键 - 值不保存
Using map with structure as key - value doesn't save
我对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
是定义这些比较运算符的一种优雅方法。
相关文章:
- 删除一个线程上有数百万个字符串的大型哈希映射会影响另一个线程的性能
- 在全局变量中保存类的实例以重新创建类(创建"backup")
- 如何在选项卡视图Qt中设置一个新项目,并保存以前的项目
- C++映射:具有自定义类的运算符[]不起作用(总是返回0)
- 将函数类成员映射到类本身内部
- 如何在 C# 中映射双 C 结构指针?
- 如何在C++中使用结构生成映射
- 使用std::函数映射对象方法
- 如何加载(或映射)文件部分的最大大小,但适合在Windows上的RAM
- 如何使用OpenCV将RBG图像转换为HSV,并将H、S和V值保存为C++中的3个独立图像
- C++映射分割错误(核心转储)
- 内联映射初始化的动态atexit析构函数崩溃
- 使用"std::unordereded_map"映射到"std::list"对象
- 类中的C++映射不会保存新键
- 如何将 STL 映射保存到文件C++
- 映射的迭代器不保存正确的值
- 增强将未定义的映射保存到磁盘的能力
- C++,如何使用映射来保存多个整数值
- 使用带有结构的映射作为键 - 值不保存
- 保存类模板化函数指针内映射