C++ Sort类成员的传递

C++模板中提供了sort方法,通常有两种方法:传递函数,传递一个对象。ios

第一种方法:函数函数

bool compare(const string &strLeft, const string &strRight)
{
  return strLeft<strRight;
}

int main()
{
  vector<string> vtstrTest;

      vtstrTest.push_back(...);

  std::sort(vtstrTest.begin(),vtstrTest.end(),compare);

  return 0;
}

注意:这里的compare函数是全局函数,而不是成员函数。this

 

第二种方法spa

代码以下:指针

#include <stdio.h>
#include <stdlib.h>  
#include <string.h>
#include <iostream>
#include <vector>
#include<algorithm>

using namespace std;

class SortTest
{
public:
    SortTest(){}
    void run()
    {
        VtSort();
    }
private:
    void VtSort();

    struct SortDesc
    {
        bool operator() (const string &left, const string &right)
        {
            return left > right;
        }
    };
};

void SortTest::VtSort()
{
    vector<string> vtTemp;
    vtTemp.push_back("abcef");
    vtTemp.push_back("12348");
    vtTemp.push_back("$#@!");
    std::sort(vtTemp.begin(),vtTemp.end(),SortDesc());

    for(int i =0; i<vtTemp.size(); ++i)
    {
        cout<<vtTemp[i]<<endl;
    }
}

int main()
{
    SortTest test;
    test.run();
    return 0;
}

上面代码的运行结果:code

abcef
12348
$#@!对象

注意,这里不能sort中不能传递类的成员函数指针,而是传递的一个对象。由于C++模板获取不到类的成员函数指针,类型成员函数指针都隐含了this指针。blog

相关文章
相关标签/搜索