当前位置:网站首页>将自定义类型作为关联容器的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<并不是关心它们的顺序,而是保证唯一,所以通常可以实现为按字典顺序比较即可。
边栏推荐
- 处理List<Map<String, String>>类型
- 如何将 DevSecOps 引入企业?
- TSF微服务治理实战系列(一)——治理蓝图
- The cost of automated testing is high and the effect is poor, so what is the significance of automated testing?
- 7.18 Day23----标记语言
- Unity自动生成阻挡Collider的GameObject工具
- 力扣:63. 不同路径 II
- 注意!软件供应链安全挑战持续升级
- The symbol table
- The Road to Ad Monetization for Uni-app Mini Program Apps: Full Screen Video Ads
猜你喜欢

Cannot read properties of null (reading 'insertBefore')

TSF微服务治理实战系列(一)——治理蓝图

C1认证之web基础知识及习题——我的学习笔记

7.16 Day22---MYSQL (Dao mode encapsulates JDBC)

The difference between px, em, and rem

谷粒商城-基础篇(项目简介&项目搭建)

企业需要知道的5个 IAM 最佳实践

OpenSSF 安全计划:SBOM 将驱动软件供应链安全

(Kettle) pdi-ce-8.2 连接MySQL8.x数据库时驱动问题之终极探讨及解决方法分析
![[Evaluation model] Topsis method (pros and cons distance method)](/img/e7/c24241faced567f3e93f6ff3f20074.png)
[Evaluation model] Topsis method (pros and cons distance method)
随机推荐
Performance testing with Loadrunner
谷粒商城-基础篇(项目简介&项目搭建)
C Expert Programming Chapter 4 The Shocking Fact: Arrays and pointers are not the same 4.2 Why does my code not work
4.1 声明式事务之JdbcTemplate
腾讯136道高级岗面试题:多线程+算法+Redis+JVM
4.3 基于注解的声明式事务和基于XML的声明式事务
9、动态SQL
warning C4251: “std::vector&lt;_Ty&gt;”需要有 dll 接口由 class“Test”的客户端使用错误
【论文阅读笔记】无监督行人重识别中的采样策略
As soon as flink cdc is started, the CPU of the source Oracle server soars to more than 80%. What is the reason?
音视频相关基础知识与FFmpeg介绍
力扣:509. 斐波那契数
C Expert Programming Chapter 4 The Shocking Fact: Arrays and pointers are not the same 4.1 Arrays are not pointers
如何低成本修bug?测试左移给你答案
Embedded system driver primary [4] - under the basis of character device driver _ concurrency control
Unity Visual Effect Graph入门与实践
Resolved error: npm WARN config global `--global`, `--local` are deprecated
MySQL日期函数
MySQL date functions
【问题解决】同一机器上Flask部署TensorRT报错记录