【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;
相关推荐
And_Ii17 小时前
LCR 168. 丑数
c++
CoderMeijun17 小时前
C++ 时间处理与格式化输出:从 Linux 时间函数到 Timestamp 封装
c++·printf·stringstream·时间处理·clock_gettime
tankeven21 小时前
HJ176 【模板】滑动窗口
c++·算法
OxyTheCrack21 小时前
【C++】一文详解C++智能指针自定义删除器(以Redis连接池为例)
c++·redis
whitelbwwww1 天前
C++基础--类型、函数、作用域、指针、引用、文件
开发语言·c++
leaves falling1 天前
C/C++ const:修饰变量和指针的区别(和引用底层关系)
c语言·开发语言·c++
tod1131 天前
深入解析ext2文件系统架构
linux·服务器·c++·文件系统·ext
不想写代码的星星1 天前
C++ 类型萃取:重生之我在幼儿园修炼类型学
c++
比昨天多敲两行1 天前
C++11新特性
开发语言·c++
xiaoye-duck1 天前
【C++:C++11】核心特性实战:详解C++11列表初始化、右值引用与移动语义
开发语言·c++·c++11