注册 登录
编程论坛 C++教室

C++标准库算法从小到大排序,sort( s.begin(),s.end(),isShorter )为什么没有向isShorter函数传递参数

令狐少侠56 发布于 2016-11-04 10:18, 1530 次点击
将字符串按照长短从小到大排序
程序代码:
bool isShorter(   const string &s1, const string &s2    )
{
    return s1.size( ) < s2.size( )  ;
}
int  main(   )
{
    vector<string>  sVec{ "the","quick","red","fox","jumps","over","the","slow","red","turtle" };
    sort(sVec.begin(), sVec.end(), isShorter );
    for (vector<string>::iterator i = sVec.begin(); i != sVec.end(); ++i) {
        cout << *i << "  ";
    }cout << endl;

    return 0;
}

C++标准库算法从小到大排序,sort( s.begin(),s.end(),isShorter )为什么没有向isShorter函数传递参数。
2 回复
#2
rjsp2016-11-04 10:34
为什么没有向isShorter函数传递参数。
------ 你有什么证据能证明“没有向isShorter函数传递参数”
#3
rjsp2016-11-04 10:42
这个代码能看懂吗?原理是一模一样的

程序代码:
#include <stdio.h>

bool isShorter( const int& a, const int& b )
{
    return a < b;
}

void sort( int& a, int& b, bool (*comp)(const int&, const int& b) )
{
    if( comp(a,b) )
        return;

    int temp = a;
    a = b;
    b = temp;
}

int  main( void )
{
    int x[] = { 1, 2 };
    sort( x[0], x[1], isShorter );
    printf( "%d %d\n", x[0], x[1] );

    int y[] = { 2, 1 };
    sort( y[0], y[1], isShorter );
    printf( "%d %d\n", y[0], y[1] );

    return 0;
}

1