当前位置:网站首页>将自定义类型作为关联容器的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<并不是关心它们的顺序,而是保证唯一,所以通常可以实现为按字典顺序比较即可。
边栏推荐
- 嵌入式系统驱动初级【3】——字符设备驱动基础中_IO模型
- 谷粒商城-基础篇(项目简介&项目搭建)
- 力扣题解8/3
- Unity表格配置编辑工具
- idea设置识别.sql文件类型以及其他文件类型
- Get the selected content of the radio box
- Web Basics and Exercises for C1 Certification - My Study Notes
- Embedded system driver primary [3] - _IO model in character device driver foundation
- FLV格式详解
- Grain Mall - Basics (Project Introduction & Project Construction)
猜你喜欢

8.03 Day34---BaseMapper query statement usage

想低成本保障软件安全?5大安全任务值得考虑

Canal mysql data synchronization

Cannot read properties of null (reading 'insertBefore')

编程大杂烩(四)

The symbol table

DP4398:国产兼容替代CS4398立体声24位/192kHz音频解码芯片

Cannot read properties of null (reading ‘insertBefore‘)

关于C#的反射,你真的运用自如嘛?

7.18 Day23 - the markup language
随机推荐
7. Execution of special SQL
phpexcel导出数据为xml
idea设置识别.sql文件类型以及其他文件类型
string类简介
TensorRTx-YOLOv5工程解读(一)
7.18 Day23----标记语言
warning C4251: “std::vector&lt;_Ty&gt;”需要有 dll 接口由 class“Test”的客户端使用错误
3面头条,花7天整理了面试题和学习笔记,已正式入职半个月
少年成就黑客,需要这些技能
MySQL date functions
EntityComponentSystemSamples学习笔记
注意!软件供应链安全挑战持续升级
The difference between px, em, and rem
C Expert Programming Chapter 4 The Shocking Fact: Arrays and pointers are not the same 4.2 Why does my code not work
Swoole学习(二)
CentOS7 —— yum安装mysql
C language -- operator details
Programming hodgepodge (4)
4.2 声明式事务概念
Unity动画生成工具