【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;
相关推荐
clint4562 天前
C++进阶(1)——前景提要
c++
夜悊2 天前
C++代码示例:进制数简单生成工具
c++
郝学胜_神的一滴2 天前
CMake 021: IF 条件判据详诠
c++·cmake
_wyt0013 天前
洛谷 B3930 [GESP202312 五级] 烹饪问题 题解
c++·gesp
玖玥拾3 天前
C/C++ 数据结构(七)栈、容器适配器
c语言·数据结构·c++··容器适配器
один but you3 天前
constexpr函数
c++
凡人叶枫3 天前
Effective C++ 条款41:了解隐式接口和编译期多态
java·开发语言·c++·effective c++
凡人叶枫3 天前
Effective C++ 条款42:了解 typename 的双重意义
java·linux·服务器·c++
小胖xiaopangss3 天前
BRpc使用
c++·rpc
-森屿安年-3 天前
63. 不同路径 II
c++·算法·动态规划