首页 > 代码库 > vector排序与查找

vector排序与查找

本示例使用比较函数,函数对象进行vector的排序与查找操作。

#include <algorithm>#include <vector>using namespace std;#define MAX_NAME_LEN    32struct 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:17no:2, name:Tom, age:16no:3, name:David, age:18no:4, name:Paul, age:15Sorted by age asc:no:4, name:Paul, age:15no:2, name:Tom, age:16no:1, name:James, age:17no:3, name:David, age:18Sorted by age desc:no:3, name:David, age:18no:1, name:James, age:17no:2, name:Tom, age:16no:4, name:Paul, age:15Student found:no:1, name:James, age:17Student found:no:2, name:Tom, age:16