gpt4 book ai didi

c++ - C++中 `std::sort`比较器的不同类型

转载 作者:IT老高 更新时间:2023-10-28 21:44:43 30 4
gpt4 key购买 nike

当我们为 std::sort 提供比较器函数时,我们使用以下重载:

template< class RandomIt, class Compare >
void sort( RandomIt first, RandomIt last, Compare comp );

其中 std::sort 的比较器函数应具有以下语法:

bool cmp(const Type1 &a, const Type2 &b);

但是你可以看到 ab 可能有不同的类型。 cppreference说:

The types Type1 and Type2 must be such that an object of type RandomIt can be dereferenced and then implicitly converted to both of them. ​

但是当我们尝试对它进行排序时,我仍然无法准确理解如何在一个数组中拥有 2 种不同的类型。

是否有人可以为 std::sort 的比较器函数提供一个不同类型的小示例?

最佳答案

这与存储在数组中的内容无关,只能存储一种类型。这与比较器功能有关。以这个为例:

struct Animal {};
struct Cat : Animal {};
struct Dog : Animal {};
struct Hound : Dog {};

bool cmp(const Animal &a, const Animal &b);

即使您有 Dogs、Cats 或 Hounds 列表,您仍然可以使用函数 对它们进行排序cmp 因为它们都是隐式可转换的。即。

std::vector<Hound> hounds;
... // fill hounds
std::sort(hounds.begin(), hounds.end(), cmp);

你甚至可以想象 Type1Type2 不一样的情况,例如:

bool cmp(const Animal &a, const Dog &b);
etc ...

虽然这种情况极为罕见。

The types Type1 (Animal) and Type2 (Dog) must be such that an object of type RandomIt (Hound) can be dereferenced and then implicitly converted to both of them. ​Which is true.

关键是对 cmp 函数可以采用相同类型的限制排除了一般性。在某些情况下,这是一个好主意,但在这种情况下,它会过于严格,并且可能会导致边缘情况实现出现问题。此外,std::sort 中使用的 cmp 函数受 Compare 的要求约束。 (可能是为了简单)。 比较要求用于各种其他事情,例如 std::max

关于c++ - C++中 `std::sort`比较器的不同类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52984999/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com