运行结果
文件列表
- student.h//声明类-属性和方法
- student.cpp//实现类方法
- main.cpp//排序算法 测试
说明
此处定义结构体或者类都一样,都可以借助算法库,自己定义排序规则,然后使用sort方法,灵活变通
代码
student.h
#ifndef STUDENT_H
#define STUDENT_H
#endif
class Student{
public:
int age;
std::string name;
public:
Student();
Student(int age,std::string name);
~Student();
};
student.cpp
#include <string>
#include "student.h"
using namespace std;
Student::Student(){}
Student::Student(int s_age,string s_name){
age = s_age;
name = s_name;
}
Student::~Student(){
}
main.cpp
#include <iostream>
#include "student.h"
#include <cstring>
#include <vector>
#include <algorithm>
using namespace std;
//年龄逆序
bool negative_sort_age(Student s1,Student s2){
return s1.age > s2.age;
}
//年龄正序
bool positive_sort_age(Student s1,Student s2){
return s1.age < s2.age;
}
//姓名逆序
bool negative_sort_name(Student s1,Student s2){
const char * ch1 = s1.name.data();
const char * ch2 = s2.name.data();
return (strcmp(ch1,ch2)>0)?true:false;
}
//姓名正序
bool positive_sort_name(Student s1,Student s2){
const char * ch1 = s1.name.data();
const char * ch2 = s2.name.data();
return (strcmp(ch2,ch1)>0)?true:false;
}
//打印student对象
void print_stu(Student &stu) {
cout << "age:" << stu.age << "name:" << stu.name << endl;
}
//打印存放student对象的vector容器
void print_v_stu(vector<Student> v){
vector<Student>::iterator it;
cout << "v.size()" << v.size() << endl;
it = v.begin();
while (it != v.end()) {
cout << "age:" << (*it).age << " name:" << (*it).name << endl;
it++;
}
}
int main(int argc, char const *argv[]) {
//容器 存储student对象
vector<Student> v;
//创建对象
Student s1(23,"pangPython");
Student s2(21,"liuliu");
Student s3(26,"sb666");
Student s4(26,"sb677");
//对象加入容器中
v.push_back(s1);
v.push_back(s2);
v.push_back(s3);
v.push_back(s4);
cout << "原始数据:" << endl;
print_v_stu(v);
cout << "-----------年龄逆序--------" << endl;
sort(v.begin(),v.end(),negative_sort_age);
print_v_stu(v);
cout << "-----------年龄正序--------" << endl;
sort(v.begin(),v.end(),positive_sort_age);
print_v_stu(v);
cout << "-----------姓名逆序--------" << endl;
sort(v.begin(),v.end(),negative_sort_name);
print_v_stu(v);
cout << "-----------姓名正序--------" << endl;
sort(v.begin(),v.end(),positive_sort_name);
print_v_stu(v);
return 0;
}