当前位置:网站首页>将自定义类型作为关联容器的key
将自定义类型作为关联容器的key
2022-08-04 05:25:00 【mo4776】
关联容器对key的要求
在关联容器中,它们通过等价来判断key是否唯一,以operator<
为判断依据,满足如下条件就判断为等价:
- 必须是“反对称的“,对
operator<
而言,如果x<y
为真,则y<x
为假,对判断式op()
而言,如果op(x,y)
为真,则op(y,x)
为假 - 必须是“可传递的“,对
operator<
而言,如果x<y
为真且y<z
为真,则x<z
为真,对判断式op()
而言,如果op(x,y)
为真且op(y,z)
为真,则op(x,z)
为真 - 必须是“非自反的“,对
operator<
而言,x<x
为假。对判断式op()
而言,op(x,x)
永远为假
内置类型本身就支持operator<
,如果要以自定定义类型来做key,就需实现operator<
操作符
自定义类型作为key
如下一个结构体
struct S {
int n;
bool f;
float d;
};
作为关联容器的key,需要定义operator<
操作符号
bool operator<(const S& rhs) const {
return n<rhs.n || f<rhs.f || d<rhs.d;
}
以S
成员变量的字典顺序进行比较,可以使用std::tie
来简化代码
bool operator<(const S& rhs) const {
return std::tie(n,f,d)<std::tie(rhs.n,rhs.f,rhs.d);
}
完整示例代码
#include <iostream>
#include <string>
#include <set>
#include <map>
#include <tuple>
struct S {
int n;
bool f;
float d;
bool operator<(const S& rhs) const {
return std::tie(n,f,d)<std::tie(rhs.n,rhs.f,rhs.d);
}
};
int main() {
std::set<S> set_of_s;
S value{
42,true, 3.14};
S v2{
42,true,3.15};
set_of_s.insert(value);
set_of_s.insert(v2);
for (auto it:set_of_s) {
std::cout<<it.d<<std::endl;
}
}
我们将自定义的类型作为关联容器的key,在绝大多数情况下,定义operator<
并不是关心它们的顺序,而是保证唯一,所以通常可以实现为按字典顺序比较即可。
边栏推荐
- 力扣:62.不同路径
- EntityComponentSystemSamples学习笔记
- Grain Mall - Basics (Project Introduction & Project Construction)
- Delphi-C端有趣的菜单操作界面设计
- MySQL log articles, binlog log of MySQL log, detailed explanation of binlog log
- Unity动画生成工具
- 即时通讯网 即时通讯音视频开发
- MySql data recovery method personal summary
- 4.2 声明式事务概念
- [One step in place] Jenkins installation, deployment, startup (complete tutorial)
猜你喜欢
FPGA学习笔记——知识点总结
(Kettle) pdi-ce-8.2 连接MySQL8.x数据库时驱动问题之终极探讨及解决方法分析
Cannot read properties of null (reading ‘insertBefore‘)
心余力绌:企业面临的软件供应链安全困境
Can 't connect to MySQL server on' localhost3306 '(10061) simple solutions
关于C#的反射,你真的运用自如嘛?
如何将 DevSecOps 引入企业?
DP4398:国产兼容替代CS4398立体声24位/192kHz音频解码芯片
Sublime Text 3 2021.8.3 个人配置
企业需要知道的5个 IAM 最佳实践
随机推荐
JNI基本使用
canal实现mysql数据同步
Swoole学习(二)
npm报错Beginning October 4, 2021, all connections to the npm registry - including for package installa
OpenRefine开源数据清洗软件的GREL语言
EventBus源码分析
Can 't connect to MySQL server on' localhost3306 '(10061) simple solutions
TSF微服务治理实战系列(一)——治理蓝图
Landing, the IFC, GFC, FFC concept, layout rules, forming method, use is analysed
MySQL数据库面试题总结(2022最新版)
DP4398:国产兼容替代CS4398立体声24位/192kHz音频解码芯片
7.13 Day20----MYSQL
如何将 DevSecOps 引入企业?
7.18 Day23----标记语言
想低成本保障软件安全?5大安全任务值得考虑
C语言 -- 操作符详解
少年成就黑客,需要这些技能
Do you think border-radius is just rounded corners?【Various angles】
PHP实现异步执行程序
The cost of automated testing is high and the effect is poor, so what is the significance of automated testing?