二元谓词只不过是一个可调用对象(包括函数或 lambda),它需要两个参数类型为容器的解引用迭代器类型。它的“作用”是为排序算法提供一个比较标准。
std::sort 算法期望此函数或函数对象返回一个可转换为 bool 的值,并且当且仅当第一个参数在排序顺序中位于第二个参数之前(所谓的 严格的弱秩序)。然后,std::sort 算法通过在单独比较元素时将谓词应用于元素,对给定的对象范围(从容器开始到结束)进行操作(排序)。
在您的情况下,如果容器是字符串向量,则取消引用的迭代器会产生 std:string,因此您的 lambda 可以正常工作。
这里是一些示例代码,展示了它如何与独立于具体类型的 lambda 一起工作,但至少需要在容器中的对象上定义 size() 操作。它还显示了如何将二进制谓词作为函数对象提供(在这种情况下,我通过反转谓词来恢复排序顺序):
#include <algorithm>
#include <iostream>
#include <string>
#include <vector>
using Words = std::vector<std::string>;
struct CompareReverse
{
bool operator() (auto lhs, auto rhs)
{
return rhs.size() < lhs.size(); // less-than reversed!
}
};
int main()
{
Words words { "red", "green", "blue", "wizard", "a", "letter", "very-long-word" };
std::sort(words.begin(), words.end(), [](auto a, auto b) { return a.size() < b.size(); });
for (auto w : words)
std::cout << w << std::endl;
std::sort(words.begin(), words.end(), CompareReverse());
for (auto w : words)
std::cout << w << std::endl;
return 0;
}