关联容器对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<
并不是关心它们的顺序,而是保证唯一,所以通常可以实现为按字典顺序比较即可。