通过重载较少的运算符对序列容器进行排序
如果没有传递排序函数,std::sort
将通过在元素对上调用 operator<
来对元素进行排序,这些元素必须返回一个上下文可转换为 bool
的类型(或者只是 bool
)。基本类型(整数,浮点数,指针等)已经在比较运算符中构建。
我们可以重载此运算符以使默认的 sort
调用适用于用户定义的类型。
// Include sequence containers
#include <vector>
#include <deque>
#include <list>
// Insert sorting algorithm
#include <algorithm>
class Base {
public:
// Constructor that set variable to the value of v
Base(int v): variable(v) {
}
// Use variable to provide total order operator less
//`this` always represents the left-hand side of the compare.
bool operator<(const Base &b) const {
return this->variable < b.variable;
}
int variable;
};
int main() {
std::vector <Base> vector;
std::deque <Base> deque;
std::list <Base> list;
// Create 2 elements to sort
Base a(10);
Base b(5);
// Insert them into backs of containers
vector.push_back(a);
vector.push_back(b);
deque.push_back(a);
deque.push_back(b);
list.push_back(a);
list.push_back(b);
// Now sort data using operator<(const Base &b) function
std::sort(vector.begin(), vector.end());
std::sort(deque.begin(), deque.end());
// List must be sorted differently due to its design
list.sort();
return 0;
}