std::sort
场景:
1. 在使用sort排序时,有时候需要对对象的某个值进行排序,比如对类对象的某个id的int类型值或者bool类型值,其实bool类型值排序研究了半天。。
test_sort.cpp
#include <stdlib.h> #include <string.h> #include <string> #include <vector> #include <algorithm> #include <iostream> using namespace std; template <typename t> void Print (vector<t> array) { int size = array.size(); cout << "size: " << size << endl; for (int i = 0; i < size; ++i) { cout << array[i] << endl; } } class Data { friend ostream &operator<<(ostream &output, const Data* data); public: Data(){} ~Data(){} int id_; bool is_deleted_; }; ostream& operator<<( ostream& os,const Data* data) { return os << data->id_ << ":" << data->is_deleted_; } void SortString() { vector<string> array; array.push_back("abc"); array.push_back("a"); array.push_back("bc"); array.push_back("h"); //1.从小到大排序 cout << "sort with from small to big" << endl; sort(array.begin(),array.end(),std::less<string>()); Print(array); //1.从大到小排序 cout << "sort with from big to small" << endl; sort(array.begin(),array.end(),std::greater<string>()); Print(array); } void SortInt() { vector<int> array; array.push_back(4); array.push_back(5); array.push_back(1); array.push_back(2); //1.从小到大排序 cout << "sort with from small to big" << endl; sort(array.begin(),array.end(),std::less<int>()); Print(array); //1.从大到小排序 cout << "sort with from big to small" << endl; sort(array.begin(),array.end(),std::greater<int>()); Print(array); } bool CompId(Data* first,Data* second) { return first->id_ < second->id_; } bool CompBool(Data* first,Data* second) { return first->is_deleted_ > second->is_deleted_; } void SortData() { vector<Data*> array; Data *d1 = new Data(); d1->id_ = 4; d1->is_deleted_ = true; Data *d2 = new Data(); d2->id_ = 3; d2->is_deleted_ = false; Data *d3 = new Data(); d3->id_ = 1; d3->is_deleted_ = true; Data *d4 = new Data(); d4->id_ = 5; d4->is_deleted_ = false; array.push_back(d1); array.push_back(d2); array.push_back(d3); array.push_back(d4); //1.根据id_从小到大排序. sort(array.begin(),array.end(),CompId); Print(array); //1.根据is_deleted_排序,true在前面. sort(array.begin(),array.end(),CompBool); Print(array); } int main(int argc, char const *argv[]) { cout << "begin" << endl; SortInt(); SortString(); SortData(); return 0; }
输出:
begin sort with from small to big size: 4 1 2 4 5 sort with from big to small size: 4 5 4 2 1 sort with from small to big size: 4 a abc bc h sort with from big to small size: 4 h bc abc a size: 4 1:1 3:0 4:1 5:0 size: 4 1:1 4:1 3:0 5:0