算法入门 --- 结构体构造自定义排序
结构体在简单算法竞赛常用于存储一个对象的多个属性,比如一个点的坐标与权重等等。
PAT就常考察这方面的应用。
基本使用与构造方法
struct stu {
string name;
int age;
string tel;
stu(string name, int age, string tel) {
this->name = name;
this->age = age;
this->tel = tel;
}
};
我们在结构体中定义了一个构造函数,这个方便我们在插入数据的时候直接构造。以下面为例。
vector<stu> Q;
Q.push_back(stu("person1", 18, "12344"));
需要注意的是如果我们使用的是数组而非vector来存储的话,需要把构造函数删掉才能使用。
构造比较器
这个是结合sort函数使用的,达到排序的效果。
传进去的参数是两个结构体对象。
bool cmp(const stu &p1, const stu &p2) {
// 年龄相同按照Tel从小到大
if (p1.age == p2.age) {
return p1.tel < p2.tel;
}
//按年龄从小到大
return p1.age < p2.age;
}
记住<是升序排列就行了。。。
完整测试代码
//
// Created by 29273 on 2021-03-17.
//
#include "bits/stdc++.h"
using namespace std;
struct stu {
string name;
int age;
string tel;
stu(string name, int age, string tel) {
this->name = name;
this->age = age;
this->tel = tel;
}
};
bool cmp(const stu &p1, const stu &p2) {
// 年龄相同按照Tel从小到大
if (p1.age == p2.age) {
return p1.tel < p2.tel;
}
//按年龄从小到大
return p1.age < p2.age;
}
int main() {
vector<stu> Q;
Q.push_back(stu("person1", 18, "12344"));
Q.push_back(stu("person2", 13, "123446"));
Q.push_back(stu("person2", 13, "1234467"));
Q.push_back(stu("person3", 12, "1234677"));
Q.push_back(stu("person4", 4, "1234677"));
sort(Q.begin(), Q.end(), cmp);
for (stu i : Q) {
cout << i.name << " " << i.age << " " << i.tel << endl;
}
return 0;
}

浙公网安备 33010602011771号