Chinaunix首页 | 论坛 | 博客
  • 博客访问: 487078
  • 博文数量: 77
  • 博客积分: 1047
  • 博客等级: 少尉
  • 技术积分: 898
  • 用 户 组: 普通用户
  • 注册时间: 2011-08-25 17:16
文章分类

全部博文(77)

文章存档

2016年(2)

2013年(2)

2012年(33)

2011年(40)

分类:

2012-05-27 03:13:39

//描述:C++ STL 的应用示例

//作者:

//发布日期:2006年3月25日

//文件名:vector.cpp

#include
#include
#include
#include
using namespace std;

struct employee
{
//Member Function
public:
 employee(long eID, string e_Name, float e_Salary);

//Attribute
public:
 long ID;                  //Employee ID
 string name;              //Employee Name
 float salary;            //Employee Salary
};

employee::employee(long eID, string e_Name, float e_Salary) : ID(eID), name(e_Name), salary(e_Salary) {}

//compare函数是对vector容器中存储的员工资料按工资进行排序的谓词
bool compare(const employee &a, const employee &b)
{
 return (a.salary > b.salary);
}

//ga8000函数是判断工资是否大于8000的谓词

bool ga8000(const employee &a)
{
 return (a.salary > 8000);
}

//定义一个元素类型为employee的vector

typedef vector EMPLOYEE_VECTOR;

//定义一个随机访问迭代器类型
typedef vector::iterator EMPLOYEE_IT;

//定义一个反向迭代器类型
typedef vector::reverse_iterator REVERSE_EMPLOYEE_IT;

//output_vector函数正向输出vector的所有元素

void output_vector(EMPLOYEE_VECTOR employ)
{
 EMPLOYEE_IT it;
 for (it = employ.begin(); it != employ.end(); it++)
 {
  cout << (*it).ID << '\t' << (*it).name << '\t' << (*it).salary << endl;
 }
}

 

//reverse_output_vector函数逆向输出vector的所有元素

void reverse_output_vector(EMPLOYEE_VECTOR employ)
{
 REVERSE_EMPLOYEE_IT it;
 for (it = employ.rbegin(); it != employ.rend(); it++)
 {
  cout << (*it).ID << '\t' << (*it).name << '\t' << (*it).salary << endl;
 }
}


int main(int argc, char* argv[])
{
 EMPLOYEE_VECTOR employ;

   //下面的三个语句分别构造一个employee对象,并依次插入到vector容器对象(employ)
   employ.push_back(employee(100, "luojiafeng", 10000));
   employ.push_back(employee(101, "liujie", 8000));
   employ.push_back(employee(102, "zhangshan", 8800));

   //按compare谓词对vector进行排序
   sort(employ.begin(), employ.end(), compare);

   //输出排序后的vector的所有元素
   output_vector(employ);

   //逆向输出vector的所有元素
   reverse_output_vector(employ);
  

   //统计并输出工资大于8000的人数
   int i = count_if(employ.begin(), employ.end(), ga8000);
      cout << "goog zi da yu 8000 de you " << i << "wei!" << endl;


 return 0;
}

阅读(1083) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~