是否可以将std :: sort与带有额外参数的sort函数一起使用?

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是返回一个在调用时调用绑定函数的对象,可选地使用更改的参数.您可以使用它来更改参数顺序,添加可选参数或将参数设置为特定的固定值.

  • @Loopunroller如果你想编写更多的代码来实现相同的结果,当然可以去吧,但是当有一个标准的库函数可以满足我的需求时,我没有理由不使用它.我不确定你所指的是什么性能问题,所以我既不能确认也不能否认这些问题是真实的. (2认同)

Pra*_*han 6

由于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)

  • 为提供适用于 C++03 的方法点赞。遗憾的是,并非所有人都在使用 C++11 或更高版本并且可以访问 std::bind()。 (2认同)