面试题答案
一键面试- 比较函数:
#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;
}
}
};
- 在定义
map
时使用这个比较函数:
int main() {
std::map<MyStruct, int, CompareMyStruct> myMap;
// 插入元素等操作
return 0;
}
在定义std::map
时,第三个模板参数传入CompareMyStruct
,这样std::map
在进行键的比较时就会使用我们自定义的比较逻辑,先按id
升序排序,如果id
相同则按name
字典序升序排序。