MST

星途 面试题库

面试题:C++ map自定义键类型的比较规则

假设我们有一个自定义结构体`MyStruct`作为`std::map`的键类型,结构体定义如下:`struct MyStruct { int id; std::string name; };`。现在要在`std::map<MyStruct, int>`中,先按`id`升序排序,如果`id`相同则按`name`字典序升序排序,写出完整的比较函数并说明如何在定义`map`时使用这个比较函数。
40.9万 热度难度
编程语言C++

知识考点

AI 面试

面试题答案

一键面试
  1. 比较函数
#include <iostream>
#include <map>
#include <string>

struct MyStruct {
    int id;
    std::string name;
};

struct CompareMyStruct {
    bool operator()(const MyStruct& a, const MyStruct& b) const {
        if (a.id != b.id) {
            return a.id < b.id;
        } else {
            return a.name < b.name;
        }
    }
};
  1. 在定义map时使用这个比较函数
int main() {
    std::map<MyStruct, int, CompareMyStruct> myMap;
    // 插入元素等操作
    return 0;
}

在定义std::map时,第三个模板参数传入CompareMyStruct,这样std::map在进行键的比较时就会使用我们自定义的比较逻辑,先按id升序排序,如果id相同则按name字典序升序排序。