结构体排序
如果需要降序
bool cmp(int x, int y){
return x>y;
}
// 首先定义排序规则,然后使用重载。
sort(a, a+len, cmp);
对于结构体
strucr E{
int age;
int score;
}buf[1000];
- 重写操作符
// 定义在结构体内
bool operator <(const E&b) const{
if(score!=b.score) return score<b.score;
else return age<b.age;
}
- cmp 函数
bool cmp(E a, E b){
if(a.score != b.score) return a.score<b.score;
elsr return a.age<b.age;
}
日期类型处理
写一个数组保存日期天数
#define ISYEAR(x) x%100!=0 && x%4==0 || x%400==0?1:0
int dayofmonth[13][2]={
0,0,
31,31, //1
28,29,
31,31,
30,30,
31,31,
30,30, //6
31,31,
31,31
30,30,
31,31,//10
30,30,
31,31
};
struct Date{
int Day;
int Month;
int Year;
void nextDay(){
Day++;
if(Day > dayofmonth[Month][ISYESR(Year)]{
Day = 1;
Month++;
if(Month > 12){
Month = 1;
Year++;
}
}
}
};
int buf[5001][13][32];
int main(){
Date tmp;
tmp.Day = 1;
tmp.Month = 1;
tmp.Year = 0;
int cnt = 0; // 0年1月1日 ,数组缓存距离那一天过去了多久
while(tmp.Year != 5001){
buf[tmp.Year][tmp.Month][tmp.Day] = cnt;
tmp.nextDay();
cnt++;
}
//之后输入对应的两个你那份数字,可以求他们之间的差值,也就是两个日期之间的日子数量。
}
排序
sort(nums.begin(),nums.end(),greater<int>());//从大到小排序
sort(nums.begin(),nums.end(),less<int>()) 从小到大排序
string 插入
basic_string& insert( size_type index, const CharT* s );
//index位置插入一个常量字符串
basic_string& insert( size_type index, size_type count, CharT ch );
在index位置插入count个字符ch
string erase
有三种用法:
(1)erase(pos,n); //删除从pos开始的n个字符,比如erase(0,1)就是删除第一个字符
(2)erase(position);//删除position处的一个字符(position是个string类型的迭代器)
(3)erase(first,last);//删除从first到last之间的字符(first和last都是迭代器)
字符串转为数字
注意截取长度,可能超过int 类型大小。
可以为0,1,10,100 但不能有01,02这种出现,判断方法:
将字符串利用atoi转化为int数字,然后在转化为string类型,比较长度,如果长度符合字符串长度合理,如果不想等说明数字并不合理。
图
堆排
double 比较
#include <math.h> //头文件要记得加const double EPS = 1e-6; //一般这样子就够,但有时具体题目要考虑是否要更小的
if(fabs(a-b) < EPS) //判断是否相等
if(a > b+EPS) // 判断a是否大于b,因为大的肯定大,所以即使你小的加上,还是会更大