在 C++ 中工作排序函数
working of sort function in c++
我正在阅读我的朋友代码,遇到了这部分sort(c + 1, c + n + 1, compare);
其中 c 是类客户的对象,定义为
class customer {
public:
int si;
int fi;
int pi;
};
并编写一个函数
bool compare(customer a, customer b)
{
if (a.pi < b.pi)
{
return true;
}
else if (a.pi > b.pi)
{
return false;
}
else
{
return a.fi < b.fi;
}
}
任何人都可以解释一下排序功能的工作原理以及此比较功能如何与排序功能链接。
std::sort 定义为:
template <class RandomAccessIterator, class Compare>
void sort (RandomAccessIterator first, RandomAccessIterator last, Compare comp);
// Sorts the elements in the range [first,last) into ascending order.
// The elements are compared using operator< for the first version, and comp for the second.
在您的情况下,我假设c
指的是客户集合中的一个条目,因为调用
sort(c + 1, c + n + 1, compare);
将对紧随集合中c
的客户n
排序,使用compare
确定顺序。
std::sort 将使用某种排序算法(在大多数实现中可能是快速排序)为您执行排序。为了做到这一点,它需要能够比较两个元素。这就是compare
函数发挥作用的地方:
Binary function that accepts two elements in the range as arguments,
and returns a value convertible to bool. The value returned indicates
whether the element passed as first argument is considered to go before
the second in the specific strict weak ordering it defines.
在您的情况下,compare
函数将按pi
的升序和fi
的升序(在相等的pi
内)对客户进行排序。
在C++ std::sort 是一个标准的库函数,通常使用快速排序来实现。它作为模板函数实现,此重载在比较器的类型上模板化,然后该函数将可调用对象作为其第三个参数,并将其用作排序的比较函数。通常,这意味着编译器将能够将比较函数内联到排序函数模板的模板实例化中,尽管它最终可能成为函数调用。
相关文章:
- 如何计算此排序函数的时间复杂度?
- 什么是自定义比较器以及如何在 C++ 的排序函数中使用它?
- 自定义排序函数中的堆溢出
- 分段 排序函数实现中的错误
- 使用排序函数 c++ 对字符数组进行排序
- 类中的排序函数
- 数组为此合并排序函数提供了正确的输出,但向量给出了不正确的输出.出了什么问题?
- 快速排序函数在快速排序算法中如何工作?
- 解释标准库排序函数C++的比较谓词的工作原理?
- C++ wrt 字符串中的 STL 排序函数
- 排序函数和优先级队列 C++ 中的比较器
- 为什么当我们使用等于'='符号比较器函数时,c ++的内置排序函数不起作用?
- C++排序函数中的奇怪之处
- C++ 排序函数中的数组项赋值
- 瓶颈 C++ 排序函数Wi-Fi 信号
- 算法中的排序函数返回错误
- 排序函数如何在整数对的向量上工作?
- 从递归向后选择排序函数调用 max 和交换函数
- 排序函数未正确返回数组
- 如何将比较器添加到自定义排序函数