stable_sort应用例子

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

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

 


using std::vector;
using std::string;

// 定义一个Person类 ,包括姓、名,性别,年龄(为演示方便都有公有变量)
class Person
{
public:
    
string    sFirstName;
    
string    sLastName;
    
int        bSex;
    
int        iAge;        
};

typedef vector<Person> VECTOR_PERSON;

string sNames[]={"李蕾蕾","李金羽","韩鹏","郑智","周海滨","崔鹏","陶伟","徐云龙","杨智","大连实德","季铭义","张耀坤","邹捷"};


// Creation of a user-defined function object
// that inherits from the unary_function base class
// std::for_each 要用到的函数
class printinfo: std::unary_function<Person, void>
{
public:
    result_type 
operator()(argument_type i)
    {
        std::cout 
<< "姓名:" << i.sLastName << i.sFirstName << " " << "年龄:" << i.iAge << std::endl;

    }
};

//std::stable_sort 要用到的比较大小的函数
//这里是按年龄比较!
bool CompareAge(Person p1,Person p2)
{
    
return p1.iAge<p2.iAge;
};

bool CompareLastName(Person p1,Person p2)
{
    
return p1.sLastName<p2.sLastName;
};


int main(int argc,char *argv[])
{
    VECTOR_PERSON vp;
    
int i=0;

    srand( (unsigned)time( NULL ) );
    int RANGE_MIN = 18;
    
int RANGE_MAX = 50;


    for(i=0;i<10;i++)
    {
        
int rand100 = (int)(((double) rand() / (double) RAND_MAX) * RANGE_MAX + RANGE_MIN);

        Person p;
        p.sFirstName = sNames[i].substr(2);
        p.sLastName  
= sNames[i].substr(0,2);
        p.bSex 
= 0;
        p.iAge 
= rand100;

        vp.push_back(p);
    }

    std::cout << "随机排列:" << std::endl;
    std::for_each(vp.begin(),vp.end(),printinfo());            
//循环打印出VECTOR_PERSON的所有元素!

    std::stable_sort(vp.begin(),vp.end(),CompareAge);        
// 对 VECTOR_PERSON 中的元素按年龄排序!

    std::cout 
<< " 按年龄排列:" << std::endl;

    std::for_each(vp.begin(),vp.end(),printinfo());            //循环打印出结果

    std::stable_sort(vp.begin(),vp.end(),CompareLastName);    
// 对 VECTOR_PERSON 中的元素按姓氏排序!

    std::cout 
<< " 按姓氏排列:" << std::endl;

    std::for_each(vp.begin(),vp.end(),printinfo());            //循环打印出结果

    
return 0;


}

posted @ 2010-12-27 16:15  Oo灰色调  阅读(216)  评论(0)    收藏  举报