关于将Eigen::Array2i作为unordered_map的key的问题

  最近在编写关于激光SLAM的代码时,遇见了一个问题,想将Eigen::Array2i作为unordered_map的key。于是随手一写:

std::unordered_map<Eigen::Array2i, int> hitsCountMap;
std::unordered_map<Eigen::Array2i, int> missesCountMap;

 编写时出现了错误:

error: use of deleted function ‘std::unordered_map<_Key, _Tp, _Hash, _Pred, _Alloc>::unordered_map() [with _Key = Eigen::Array<int, 2, 1>; _Tp = int; _Hash = std::hash<Eigen::Array<int, 2, 1> >; _Pred = std::equal_to<Eigen::Array<int, 2, 1> >; _Alloc = std::allocator<std::pair<const Eigen::Array<int, 2, 1>, int> >]’
   88 |    std::unordered_map<Eigen::Array2i, int> hitsCountMap;

原因是因为unordered_map 默认不能将 Eigen::Array2i 直接作为键类型使用,因为它没有默认的哈希函数和相等比较运算符。

于是自己重新hash函数:
 

struct Array2iHash {
  std::size_t operator()(const Eigen::Array2i& arr) const {
    // 自定义哈希函数
    return std::hash<int>()(arr.x()) ^ std::hash<int>()(arr.y());
  }
};

struct Array2iEqual {
  bool operator()(const Eigen::Array2i& arr1, const Eigen::Array2i& arr2) const {
    // 自定义相等比较运算符
    return arr1.x() == arr2.x() && arr1.y() == arr2.y();
  }
};

然后构造unordered_map:

std::unordered_map<Eigen::Array2i, int, Array2iHash, Array2iEqual> hitsCountMap;
std::unordered_map<Eigen::Array2i, int, Array2iHash, Array2iEqual> missesCountMap;

这样就能编译通过啦!如果对你有帮助,请点赞收藏哦,谢谢了!

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值