【c++】解决使用 std::map 时报错 no match for ‘operator<’

文章目录

    • [1. 发现问题](#1. 发现问题)
    • [2. GPT 分析问题](#2. GPT 分析问题)
    • [3. 解决问题](#3. 解决问题)

1. 发现问题

c++ 代码中使用复杂类型 std::map<Eigen::Vector2i, std::set<long unsigned int>> 时报错 no match for 'operator<' (operand types are 'const Eigen::Matrix<int, 2, 1>' and 'const Eigen::Matrix<int, 2, 1>')。

2. GPT 分析问题

这个错误是由于 std::map 默认使用 < 操作符进行比较键值,但是 Eigen::Vector2i 类型没有定义 < 操作符,因此导致编译错误。

为了在 std::map 中使用 Eigen::Vector2i 作为键类型,你需要提供一个比较函数或者自定义比较方式。你可以通过定义一个比较函数或者自定义比较对象来解决这个问题。

3. 解决问题

cpp 复制代码
std::map<Eigen::Vector2i, std::set<long unsigned int>> grids;

修改为

cpp 复制代码
struct Vector2iCompare {
    bool operator()(const Eigen::Vector2i& lhs, const Eigen::Vector2i& rhs) const {
        if (lhs.x() != rhs.x())
            return lhs.x() < rhs.x();
        return lhs.y() < rhs.y();
    }
};

// 使用自定义比较函数作为 std::map 的比较方式
std::map<Eigen::Vector2i, std::set<long unsigned int>, Vector2iCompare> grids;
相关推荐
无忧.芙桃7 小时前
C++语言原理与实践(二十三):哈希表的实现
c++·链表·哈希算法·散列表·哈希表
AvocadoZeroOneOI10 小时前
B4500 [GESP202603 三级] 凯撒密码 详细解题报告
c++·算法
whitelbwwww12 小时前
cuBLAS--CUDA高性能线性代数计算库--第一部分
c++·线性代数·gpu算力·cuda c++
eggwyw14 小时前
C++设计模式之解释器模式
开发语言·c++
我不会插花弄玉1 天前
13.多路转接epoll【由浅入深-网络】
网络·c++·epoll
郝学胜-神的一滴1 天前
Effective STL 条款03:容器中的对象复制要廉价且正确
开发语言·数据结构·c++·算法·rpc·stl
西西弗Sisyphus1 天前
C++ explicit 关键字工程实践
开发语言·c++
AIgorithmGEEK1 天前
std::unordered_map 与 std::unordered_set:接口、算法技巧与权衡 (速查)
c++·算法·哈希表·负载因子·桶·unordered_map·unordered_set
一拳一个呆瓜1 天前
【STL】头文件:<cmath>
c++·stl
草莓熊Lotso1 天前
【C++ 基于微服务的即时通讯系统】ElasticSearch 用户数据管理实现
linux·数据库·c++·elasticsearch·微服务·架构