Is it possible to use std::sort with a sort function that takes extra arguments?

Jared picture Jared · Oct 18, 2014 · Viewed 8.3k times · Source

This is something that I've been considering for a while. I've done some research and can't find anything on it, but I haven't found anything to the contrary either.

Consider the std::sort function in <algorithm>. It takes two iterators and a function pointer as arguments. So if I wanted to sort a vector of strings alphabetically, I would do something like this:

bool ascending(std::string lhs, std::string rhs) { return lhs < rhs; }

std::sort(my_vector.begin(), my_vector.end(), ascending);

The thing is that this type of sort function is case-sensitive, so would place a string beginning with lowercase 'a' after strings beginning with uppercase 'Z'. The only visible solution I see to this is creating an additional function along the lines of bool ascending_case_insensitive(). However, it would be nice if I could have a function bool ascending() with an additional bool is_case_sensitive parameter to use in sort. Is this possible?

Answer

user743382 picture user743382 · Oct 18, 2014

Where you now have

bool ascending(std::string lhs, std::string rhs);

std::sort(my_vector.begin(), my_vector.end(), ascending);

you can have

bool ascending(std::string lhs, std::string rhs, bool case_sensitive);

using namespace std::placeholders;
std::sort(my_vector.begin(), my_vector.end(), std::bind(ascending, _1, _2, false));

The point of std::bind is to return an object that when invoked, calls the bound function, optionally with altered arguments. You can use it to change argument order, add optional parameters, or set parameters to specific fixed values.