标签:des style class blog code color
本示例使用比较函数,函数对象进行vector的排序与查找操作。
#include <algorithm> #include <vector> using namespace std; #define MAX_NAME_LEN 32 struct Student { int no; char name[MAX_NAME_LEN]; int age; bool operator==(const Student& other) const { return no == other.no; } bool operator==(int studentNo) const { return no == studentNo; } }; typedef std::vector<Student> TVecStudent; Student g_students[] = { {1, "James", 17}, {2, "Tom", 16}, {3, "David", 18}, {4, "Paul", 15}, }; void InitStudent(TVecStudent& students) { students.assign(&g_students[0], &g_students[0] + sizeof(g_students)/sizeof(g_students[0])); } void PrintStudent(const Student& student) { printf("no:%d, name:%s, age:%d\n", student.no, student.name, student.age); } void PrintStudents(TVecStudent& students) { TVecStudent::const_iterator iter = students.begin(); for (; students.end() != iter; ++iter) { const Student& student = *iter; PrintStudent(student); } } // 小于比较函数运算子 bool lessStudentAge(const Student& lft, const Student& rht) { return lft.age < rht.age; } // 大于比较函数对象运算子 struct GreaterAgeSorter { bool operator()(const Student& lft, const Student& rht) { return lft.age > rht.age; } }; // 学号查找函数对象运算子 struct StudentNoFinder { StudentNoFinder(int no) { m_no = no; } bool operator()(const Student& student) const { return student.no == m_no; } private: int m_no; };
测试代码:
void testVector() { TVecStudent students; InitStudent(students); printf("Origin students:\n"); PrintStudents(students); std::sort(students.begin(), students.end(), lessStudentAge); printf("\n\nSorted by age asc:\n"); PrintStudents(students); std::sort(students.begin(), students.end(), GreaterAgeSorter()); printf("\n\nSorted by age desc:\n"); PrintStudents(students); TVecStudent::const_iterator itFind; itFind = std::find(students.begin(), students.end(), 1); if (students.end() != itFind) { printf("\n\nStudent found:\n"); PrintStudent(*itFind); } itFind = std::find_if(students.begin(), students.end(), StudentNoFinder(2)); if (students.end() != itFind) { printf("\n\nStudent found:\n"); PrintStudent(*itFind); } } int main() { testVector(); return 0; }
输出结果:
Origin students: no:1, name:James, age:17 no:2, name:Tom, age:16 no:3, name:David, age:18 no:4, name:Paul, age:15 Sorted by age asc: no:4, name:Paul, age:15 no:2, name:Tom, age:16 no:1, name:James, age:17 no:3, name:David, age:18 Sorted by age desc: no:3, name:David, age:18 no:1, name:James, age:17 no:2, name:Tom, age:16 no:4, name:Paul, age:15 Student found: no:1, name:James, age:17 Student found: no:2, name:Tom, age:16
标签:des style class blog code color
原文地址:http://www.cnblogs.com/shokey520/p/3790382.html