Sorting has two forms:
- A “standard” form that uses the default comparison for comparing items
- A “custom” form that uses a Compare function or object to perform the comparison
template <class RandomAccessIterator>
void sort (RandomAccessIterator first, RandomAccessIterator last);
template <class RandomAccessIterator, class Compare>
void sort (RandomAccessIterator first, RandomAccessIterator last, Compare comp);
Also, we have a lot of control over how we sort
• Using the “natural” comparator like < for numbers
• Using a custom comparator (function or object) for more refined sorting
• The “custom” Compare can either be a function or an object
• In either case, we end up with a function or method that returns true
if one item is “less than” another item – the custom Compare defines
what “less than” mean
// sort algorithm example
#include <iostream> // std::cout
#include <algorithm> // std::sort
#include <vector> // std::vector
bool myfunction (int i,int j) { return (i<j); }
struct myclass {
bool operator() (int i,int j) { return (i<j);}
} myobject;
int main () {
int myints[] = {32,71,12,45,26,80,53,33};
// 32 71 12 45 26 80 53 33
std::vector<int> myvector (myints, myints+8);
// using default comparison (operator <):
//(12 32 45 71)26 80 53 33
std::sort (myvector.begin(), myvector.begin()+4);
// using function as comp
// 12 32 45 71(26 33 53 80)
std::sort (myvector.begin()+4, myvector.end(), myfunction);
// using object as comp
//(12 26 32 33 45 53 71 80)
std::sort (myvector.begin(), myvector.end(), myobject);
// print out content:
std::cout << "myvector contains:";
for (std::vector<int>::iterator it=myvector.begin();
it!=myvector.end(); ++it) {
std::cout << ' ' << *it;
}
std::cout << std::endl;
return 0;
}
本文深入探讨了排序算法的两种形式:标准排序使用默认比较方式,定制排序通过比较函数或对象进行。详细介绍了如何使用C++标准模板库(STL)中的sort函数进行排序,包括使用自然比较符、定制比较函数及比较对象的方法。
4022

被折叠的 条评论
为什么被折叠?



