Passing extra parameters to STL sort

While attempting to solve a Quora challenge , I had the necessity to sort a vector of objects with a third parameter as a reference.

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_;
    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));

2 comments on “Passing extra parameters to STL sort

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s