vector对自定义结构体排序注意2点

// testStl.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <iostream>
#include <vector>
#include <algorithm>
#include <utility>
#include <functional>
#include <string>

using namespace std;

struct test_large : public binary_function<int, int, bool>
{
    bool operator()(int x, int y)
    {
        return (x > y);
    }
};

/* 要对结构体进行排序,重载比较操作符就行了,然后结构体就可以像基础类型一样操作了*/
typedef struct tagWorker
{
    int age;
    string name;

    bool operator < (const tagWorker &y) const
    {
        return (age < y.age);
    }

    bool operator > (const tagWorker &y) const
    {
        return (age > y.age);
    }
}Worker;

int _tmain(int argc, _TCHAR* argv[])
{
    vector<int> v1;

    v1.push_back(2);
    v1.push_back(5);
    v1.push_back(3);
    v1.push_back(4);
    v1.push_back(1);

    v1[3] = 10; 

    vector<int>::iterator iter;
    for(iter = v1.begin(); iter != v1.end(); iter++)
    {
        cout<<*iter<<", ";
    }

    cout<<endl;

    sort(v1.begin(), v1.end(), less_equal<int>());
    for(iter = v1.begin(); iter != v1.end(); iter++)
    {
        cout<<*iter<<", ";
    }

    cout<<endl;

    sort(v1.begin(), v1.end(), test_large());
    for(iter = v1.begin(); iter != v1.end(); iter++)
    {
        cout<<*iter<<", ";
    }

    cout<<endl;

    vector<int> v2(2);
    v2[0] = 1;
    v2[1] = 2;

    /* 坑:指定大小方式使用数组,数组中的所有数据都必须要初始化,否则sort会报异常 */
    /* 这个地方也是个坑,如果v2初始化成100个,但只对部分赋值了,编译的时候不会报错,但运行的时候,sort函数会报异常*/
    sort(v2.begin(), v2.end(), less_equal<int>());

    cout<<v2[0]<<", "<<v2[1]<<endl;

    vector<Worker> v3(3);
    v3[0].age = 25;
    v3[0].name = "susu";
    v3[1].age = 18;
    v3[1].name = "chaochao";
    v3[2].age = 28;
    v3[2].name = "minmin";

    //sort(v1.begin(), v1.end(), less_equal<Worker>());
    sort(v3.begin(), v3.end(), less<Worker>());

    for(int index = 0; index < v3.size(); index++)
    {
        cout<<v3[index].age<<", "<< v3[index].name<<endl;
    }

    cout<<endl;

    sort(v3.begin(), v3.end(), greater<Worker>());

    for(vector<Worker>::const_iterator iter = v3.begin(); iter != v3.end(); iter++)
    {
        cout<<iter->age<<", "<<iter->name<<endl;
    }

    return 0;
}
原文地址:https://www.cnblogs.com/liuzc/p/6542698.html