【问题标题】:can somebody explain the following syntax and how it functions?有人可以解释以下语法及其功能吗?
【发布时间】:2020-04-20 14:10:53
【问题描述】:
bool isShorter(const string &s1,const string &s2){
return s1.size() < s2.size()
}

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

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

【问题讨论】:

  • isShorter 是一个比较器 - 它告诉std::sort 这对元素中的哪一个在排序顺序中应该在另一个之前。在此示例中,字符串按长度排序,较短的字符串优先。
  • 如有疑问,请阅读文档:std::sort
  • @IgorTandetnik 但作为参数传递给sort 的函数isShorter 没有或不知道任何元素存在,因为它不包含单词。
  • 什么意思?它需要其中两个作为参数 - 这就是它需要知道的全部内容。 sort 在需要确定一对元素的顺序时调用它。
  • @IgorTandetnik 在bool isShorter 定义中是的,它确实有两个参数,但在sort 中没有提供给它的参数。由于它是可调用对象,它是否隐式提供参数?

标签: c++ string algorithm sorting containers


【解决方案1】:

本次调用标准算法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 

【讨论】:

    【解决方案2】:

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

    因此,您在这里按字符串的长度对字符串进行排序。

    【讨论】:

    • 但是sort(words.begin(),words.end(), isShorter);isShorter 的参数在哪里,因为我们没有向它传递任何东西,它怎么知道要比较什么?
    • 您将isShorter 函数对象传递给sort 函数。在sort 函数的实现中,将使用适当的参数调用isShorter。所以写sort函数的人会照顾你。
    【解决方案3】:

    来自cppreference:最后一个参数是comp

    比较函数对象(即满足 Compare) 的要求,如果第一个参数是,则返回 true 小于(即之前订购)第二个。的签名 比较函数应该等价于:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-01-07
      • 1970-01-01
      • 1970-01-01
      • 2011-06-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多