有人可以解释以下语法及其功能吗?

can somebody explain the following syntax and how it functions?

本文关键字:功能 解释 语法      更新时间:2023-10-16
bool isShorter(const string &s1,const string &s2){
return s1.size() < s2.size()
}

isShorter在这里的作用是什么,它是如何实施的?

sort(words.begin(),words.end(), isShorter);

isShorter称为比较器。比较器是可调用的,它将一个类型的两个元素作为输入,如果第一个元素应该在第二个元素之前返回 true,否则返回 false。

所以在这里你按字符串的长度对字符串进行排序。

来自 cpp首选项: 最后一个参数是comp

比较函数对象(即满足Comparetrue( 的要求,如果第一个参数是 小于(即在之前排序(第二个。签名 比较函数应等效于以下内容:

bool cmp(const Type1 &a, const Type2 &b);

对于您的情况,Type1 = Type2 = string。排序算法使用此函数来确定排序。

标准算法的这种调用std::sort

sort(words.begin(),words.end(), isShorter);

使用函数isShorter作为比较函数按升序按容器中存储的字符串的长度对存储在容器中的字符串进行排序,以比较容器中两个字符串的长度。

这是一个演示程序

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
bool isShorter( const std::string &s1, const std::string &s2 )
{
return s1.size() < s2.size();
}
int main() 
{
std::vector<std::string> v = { "123", "1", "12" };
for ( const auto &s : v ) std::cout << s << ' ';
std::cout << 'n';
std::sort( v.begin(), v.end(), isShorter );
for ( const auto &s : v ) std::cout << s << ' ';
std::cout << 'n';
return 0;
}

它的输出是

123 1 12 
1 12 123