STL sort使用

来源:互联网 发布:保定广电网络客服电话 编辑:程序博客网 时间:2024/06/06 16:04

 

#include <cstdlib>

#include <iostream>

#include <vector>

#include <algorithm>

#include <iterator>

 

using namespace std;

 

typedef struct _NODE

{

    int id;

    int val;

 

    _NODE(int id, int val): id(id), val(val){};

 

    friend ostream& operator <<(ostream &os, const _NODE &node)

    {    

        return os << node.val << " ";

    }

}NODE;

 

typedef struct _ANY

{

    int id;

    int val;

 

    _ANY(int id, int val): id(id), val(val){};

 

    friend bool operator <(const _ANY &an, const _ANY &any)

    {

         return an.val < any.val;

    }

 

    friend ostream& operator <<(ostream &os, const _ANY &an)

    {    

        return os << an.val << " ";

    }

 

}ANY;

 

bool cmp(const NODE &nod, const NODE &node)

{

     return nod.val < node.val;

}

 

class valCmp

{

public:

    bool operator()(const NODE &nod, const NODE &node)

    {

         return nod.val < node.val;

    }

};

 

int main(int argc, char *argv[])

{

    vector<NODE> node;

    vector<ANY> any;

 

    for(int i=0; i<10; i++)

    {

        NODE temp(i, rand() % 100);

        ANY tempA(i, rand() % 100);

 

        node.push_back(temp);

        any.push_back(tempA);

    }

 

    //sort(node.begin(), node.end(), cmp);

    sort(node.begin(), node.end(), valCmp());

    sort(any.begin(), any.end());

 

    ostream_iterator<NODE> output(cout, " ");

    copy(node.begin(), node.end(), output);

    cout << endl;

 

    ostream_iterator<ANY> output1(cout, " ");

    copy(any.begin(), any.end(), output1);

    cout << endl;

 

    system("PAUSE");

    return EXIT_SUCCESS;

}

利用sort对自定义的结构进行排序的三种方式:

1.重载自定义结构的<操作符, 这种适合于按照特定的字段进行比较的情况...

2.写一个单独的cmp()函数...

3.写一个单独的类, 重载()操作符...

原创粉丝点击