有人可以解释以下语法及其功能吗?
can somebody explain the following syntax and how it functions?
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
:
比较函数对象(即满足
Compare
true
( 的要求,如果第一个参数是 小于(即在之前排序(第二个。签名 比较函数应等效于以下内容: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
相关文章:
- 在执行其他功能的同时播放动画(LED矩阵和Arduino/ESP8266)
- 多态性和功能结合
- 请解释"函数1(p1,p2,p3);"的输出
- 带内存和隔离功能的SQLite
- 请解释这句话(cout<<1+int((a<b)^((b-a)&1) )<<endl
- 在CMakeLists.txt的安装功能中使用.cmake文件有什么用
- 类模板的成员功能的定义在单独的TU中完全专业化
- 有人可以解释以下语法及其功能吗?
- 有人可以解释一下复制功能的作用吗?
- MPI_Op_create:候选功能不可行.自定义结构指针不能解释为空指针
- C 功能具有参考参数错误的迭代器错误.寻求解释
- 两个功能并没有花时间我期望的,因为它们的复杂性很大,任何人都可以解释原因
- 有人能解释一下这个功能是如何工作的吗
- 更好地解释C++指针功能
- QT应用程序无法解释使用SQLite插入功能
- 解释这个闰年功能C++
- 请解释此功能
- 有人能用WinSock解释一下可写可读的fd_sets的功能吗
- 有人能解释一下这个功能吗
- C++ 需要解释此功能