文章目录
一、 知识点
1. 输入、输出
scanf 除 %c
以外,其他输入以空格或换行符为结束判断标志。
double 输入 %lf
输出 %f
%d
默认左对齐 %md
m位右对齐 %-md
m位左对齐 %0md
以0补齐
2. 小技巧
2.1 C++的引用
void change(int &x){
x = 1;
}
2.2 结构体的构造函数
构造函数,用于初始化结构体,不需要返回类型,函数名与结构体名相同。
struct studentInfo {
int id;
char gender;
//默认生成的构造函数
studentInfo() {
}
};
所以可以这样写构造函数:
struct studentInfo {
int id;
char gender;
//下面的参数用以对结构体内部变量赋值
studentInfo(int _id, char _gender) {
//赋值
id = _id;
gender = _gender;
}
};
//或者这样写
struct studentInfo {
int id;
char gender;
//下面的参数用以对结构体内部变量赋值
studentInfo(int _id, char _gender) :
id(_id), gender(_gender) {}
};
于是可以在需要时直接对结构体变量进行赋值了:
studentInfo stu = studentInfo(10086, 'M');
注意,在重新定义构造函数后,就不能不经初始化就定义结构体变量,也就是说原有的构造函数被覆盖,这时可以考虑使用多个构造函数。
struct studentInfo {
int id;
char gender;
//用以不初始化就定义结构体变量
studentInfo() {
}
//只初始化gender
studentInfo(char _gender) {
gender = _gender;
}
//同时初始化id和gender
studentInfo(int _id, char _gender) {
id = _id;
gender = _gender;
}
};
2.3 浮点数的比较
const double eps = 1e-8;
#define Equ(a, b) ((fabs((a) - (b)) < (eps))) //等于,其他情况类似
2.4 判断大数的奇偶性
if (num & 1) //用于判断奇偶数会更快
3. 函数相关
3.1 一般函数
floor(double x); //向下取整
ceil(double x); //向上取整
memest(数组名, 值, sizeof(数组名)); //需要头文件string.h 按字节赋值 建议使用0或-1
fill(容器名, 容器名+长度, 0); //需要头文件<algorithm>
sscanf(str, "%d", &n); //字符数组str以%d的格式写到n里
sprintf(str, "%d", n); //n以%d的格式写到字符数组str里
3.2 rand()函数
rand只能生成[0,RAND_MAX]范围内的整数,RAND_MAX是stdlib.h中的一个常数。
#include <cstdio>
#include <ctime>
#include <cstdlib>
#include <cmath>
int main() {
srand((unsigned)time(NULL)); //随机数的种子
int a, b;
scanf("%d %d", &a, &b);
//直接生成[a,b]内的随机数(不能超过RAND_MAX)
int n = rand() % (b - a + 1) + a;
//生成大范围的[a,b]内的随机数
int m = (int)(round(1.0 * rand() / RAND_MAX * (b - a) + a));
printf("%d\n%d", n, m);
}
3.3 C++的sort函数
sort(首元素地址,尾元素地址的下一个地址,比较函数(cmp))
,使用时需要加上如下:
#include <algorithm>
using namespace std;
其中cmp函数默认情况下是从小到大排序。
实现cmp函数:
①基本数据类型数组的排序
bool cmp(int a, int b) {
return a > b; //实现从大到小排序
}
②结构体数组的排序
如果结构体内的数据较为庞大,建议使用引用来提高效率。
struct node {
int x, y;
} ssd[10];
bool cmp(node a, node b) { //(const node &a,const node &b)
if (a.x != b.x) return a.x > b.x; //x不等时按x从大到小排序
else return a.y < b.y; //x相等时按y从小到大排序
}
③容器的排序
vector
的排序:
bool cmp(int a, int b) { //根据vector中元素的类型调整
return a > b;
}
sort(vi.begin(), vi.end(), cmp);
string
的排序:
sort(str, str+str.length()); //将string型数组按字典序从小到大输出
bool cmp(string str1, string str2) { //按string的长度从小到大排序
return str1.length() < str2.length();
}
容器的排序 vector、string、deque可以使用sort,set和map使用红黑树实现,元素本身有序。