分类: C/C++
2006-03-25 10:50:15
//描述: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
//定义一个随机访问迭代器类型
typedef vector
//定义一个反向迭代器类型
typedef vector
//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;
}