Sorting

本文深入探讨了排序算法的两种形式:标准排序使用默认比较方式,定制排序通过比较函数或对象进行。详细介绍了如何使用C++标准模板库(STL)中的sort函数进行排序,包括使用自然比较符、定制比较函数及比较对象的方法。

Sorting has two forms:

  1. A “standard” form that uses the default comparison for comparing items
  2. 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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值