Jar*_*red 5 c++ sorting algorithm stl-algorithm c++11
这是我一直在考虑的事情.我已经做了一些研究而且找不到任何东西,但我也没有发现任何相反的东西.
考虑一下这个std::sort功能<algorithm>.它需要两个迭代器和一个函数指针作为参数.所以,如果我想按字母顺序对字符串向量进行排序,我会这样做:
bool ascending(std::string lhs, std::string rhs) { return lhs < rhs; }
std::sort(my_vector.begin(), my_vector.end(), ascending);
Run Code Online (Sandbox Code Playgroud)
问题是这种类型的排序函数区分大小写,因此在以大写"Z"开头的字符串后面会放置以小写"a"开头的字符串.我看到的唯一可见的解决方案是创建一个额外的功能bool ascending_case_insensitive().但是,如果我可以在sort中使用bool ascending()带有附加bool is_case_sensitive参数的函数,那就太好了.这可能吗?
小智 13
你现在的位置
bool ascending(std::string lhs, std::string rhs);
std::sort(my_vector.begin(), my_vector.end(), ascending);
Run Code Online (Sandbox Code Playgroud)
你可以有
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));
Run Code Online (Sandbox Code Playgroud)
关键std::bind是返回一个在调用时调用绑定函数的对象,可选地使用更改的参数.您可以使用它来更改参数顺序,添加可选参数或将参数设置为特定的固定值.
由于std :: sort采用了比较仿函数的实例,因此可以使用仿函数构造函数的参数来确定其行为.例如,
class StringCompare
{
public:
StringCompare(bool is_case_sensitive=true) : is_case_sensitive(is_case_sensitive){}
bool operator()(const string&, const string&);///This would handle the comparison using the is_case_sensitive flag
private:
bool is_case_sensitive;
};
std::sort(my_vector.begin(), my_vector.end(), StringCompare(true));//case-sensitive comparison
std::sort(my_vector.begin(), my_vector.end(), StringCompare(false));//case-insensitive comparison
Run Code Online (Sandbox Code Playgroud)