Using a Comparison Function for the Key Type

本文探讨了C++中如何为关联容器指定自定义的比较操作,并解释了如何正确地声明这些操作类型。同时,文章对比了不同类型的参数声明方式及其适用场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

(这是C++系列随笔的第二篇,这一系列是我练习C++而查的资料)

extracted from C++ Primer 5th. edition pp. 425


 

Using a Comparison for the Key Type

The type of the operation that a container uses to organize its elements is part of the type of that container. To specify our own operation, we must supply the type of that operation when we define the type of an associative container (including prioroty_queue). The operation type is specified following the element type inside the angle brackets that we use to say which type of container we are defining. (We are actually required to define a parameter type not to pass an argument.)

 

Each type inside the angle brackets is just that, a type (please pay attention to this sentence). We supply a particular comparison operation (more generally, a callable object: a pointer to function or a function object) of the specified type (that must have the same type as specified inside the angle brackets, and conversely we msut specify the type inside the angle brackets the same type as the constructor argument we are going to and allowed to supply (from outside? sounds subtle...)) when we create a container.

(C++ Primer, 5th. Ed. pp. 249)


 

Related Topic:

Function Pointer Parameters

Just as with arrays, we cannot define parameters of function type but can have a parameter that is a pointer to function. As with arrays, we can write a parameter that looks like a function type (when declaring or defining a function), but it will be treated as a pointer:

 

//third parameter is a function type and is automatically treated as a pointer to function
void useBIgger(const string &s1, const string &s2, 
                bool pf(const string &, const string &));
//equivalent declaration: explicitly define the parameter as a pointer to function
void useBIgger(const string &s1, const string &s2, 
                bool (*pf)(const string &, const string &));

 

However we cannot do so when defining the type of an associative container (a parameter that looks like a functoin type will not be treated as a pointer, and thus illegal):

 

//error
priority_queue<P, vector<P>, bool (const P&, const P&)> que(cmp);
//OK
priority_queue<P, vector<P>, bool (*) (const P&, const P&)> que(cmp);
//a simplified declaration using decltype
priority_queue<P, vector<P>, decltype(cmp)*> que(cmp);

 

转载于:https://www.cnblogs.com/Patt/p/4831021.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值