sort
1. Common sort
Example from cplusplus.com:
// 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};
std::vector<int> myvector (myints, myints+8); // 32 71 12 45 26 80 53 33
// using default comparison (operator <):
std::sort (myvector.begin(), myvector.begin()+4); //(12 32 45 71)26 80 53 33
// using function as comp
std::sort (myvector.begin()+4, myvector.end(), myfunction); // 12 32 45 71(26 33 53 80)
// using object as comp
std::sort (myvector.begin(), myvector.end(), myobject); //(12 26 32 33 45 53 71 80)
// print out content:
std::cout << "myvector contains:";
for (std::vector<int>::iterator it=myvector.begin(); it!=myvector.end(); ++it)
std::cout << ' ' << *it;
std::cout << '\n';
return 0;
}
2. Passing extra parameters to STL sort
Refer to: https://varrunr.wordpress.com/2012/07/30/passing-extra-parameters-to-stl-sort/
//My vector looked like
class Topic;
class Query;
vector<Topic> list_topics;
//I needed to sort the vector list_topics using a Query object as reference. But traditionally, a comparator function takes in only 2 arguments of the same type as the elements that are being sorted.
bool compareTopics(const Topic t1 , const Topic t2){}; // Traditional comparator
sort( list_topics.begin() , list_topics.end() , compareTopics);
//I needed to pass in a third parameter to make it,
bool compareTopics(const Topic t1, const Topic t2, Query query){
// compare here
};
//In order to do this, we need to make use of functors i.e an object that can be called like a regular function. To implement this in C++, we need to define a class and implement to () operator function, while passing the extra arguments we need to the class constructor.
class TopicSorter{
Query query_;
public:
TopicSorter(Query query){ query_ = query; }
bool operator()(Topic t1, Topic t2) const {
return compareTopics( t1 , t2 , query_);
}
};
//Now we can sort the vector of objects
Query query;
sort(list_topics.begin() , list_topics.end() , TopicSorter(query));