这里是一些代码段以及常用指令的集合,可能是来自网上的,也可能是平时的积累,常看常新,learning by doing ~
C++
1 |
万能头函数,包含了C++标准库中几乎所有的头文件。
优点可以简化代码,可以节省一些输入的时间,在编程竞赛中很常用。
缺点是包含了很多不必要的头文件,可能会导致编译时间增加,实际的项目开发中不推荐使用。
1 | ios::sync_with_stdio(false); |
用来优化输入/输出流的一个方法,在使用输入/输出流之前调用,并且只需要调用一次。
调用后C++的标准输入/输出流和C的标准输入/输出流就不再同步,优点是由于取消了同步,cin
和cout
的性能会得到提升。
同时这意味着不能再混合使用cin
/cout
和scanf
/printf
,否则可能会导致未定义的行为。
1 | std::priority_queue<int> pq; |
priority_queue
是C++标准库中的一个容器适配器,它提供了优先队列的功能。
优先队列是一种特殊的队列,每次出队的元素是当前队列中优先级最高的元素。
默认创建一个最大堆,也就是说每次出队的元素是当前队列中的最大元素,可以通过提供自定义的比较函数来改变这个行为。
1 | cout << fixed << setprecision(2) << floatNum << endl; |
将浮点数a以固定的格式和2位的精度输出,然后输出一个换行符。
例如,如果a的值为3.14159,那么这段代码会输出3.14。
1 | cout << year << "-" << setw(2) << setfill('0') << month << "-" << setw(2) << setfill('0') << day << endl; |
输出一个日期,日期的格式为”年-月-日”,并且月和日都是两位数,如果不足两位则在前面补0。
例如,如果year的值为1999,month的值为9,day的值为14,那么这段代码会输出1999-09-14。
1 | std::string str = "123"; |
string → int:
std::stoi
string → float:std::stof
int → string:std::to_string
float → string:std::to_string
1 | char str[] = "123"; |
用于数字和字符串之间转换的函数
ASCII to integer:atoi()
,接收字符数组形式的字符串,转换为对应的整数。如果字符串不能转换为有效的整数,或者字符串为空,atoi()
函数将返回 0。
integer to ASCII:itoa()
,接收一个整数和一个字符数组,并将证书转换为字符串传出在字符数组中。itoa()
还接受一个第三个参数,用于指定转换的基数(例如,10 表示十进制,16 表示十六进制)
1 | std::vector<int> vec = {1, 2, 2, 3, 3, 3, 4, 4, 4, 4}; |
使用
std::sort
和std::unique
函数来去除std::vector
中的重复元素。
首先,使用std::sort
函数对std::vector
进行排序。这是因为std::unique
函数只能去除相邻的重复元素,所以需要先进行排序。
然后,使用std::unique
函数去除std::vector
中的重复元素。std::unique
函数会将所有重复的元素移到std::vector
的末尾,并返回一个迭代器指向第一个重复元素。
最后,使用std::vector::erase
函数删除所有重复的元素。
1 | int max_it = *std::max_element(v.begin(), v.end()); |
找到
std::vector
中的最大值并将其赋值给max_itstd::max_element
函数返回一个指向最大元素的迭代器,使用*操作符来获取这个元素的值。
注意的是,如果std::vector
是空的,那么std::max_element
会返回v.end()
,这是一个无效的迭代器,不能对它进行解引用。
1 | std::numeric_limits<int>::min() |
常量表达式,它返回int类型可以表示的最小值,通常是-2147483648。
同理std::numeric_limits<int>::max()
返回int类型可以表示的最大值,std::numeric_limits<double>::epsilon()
返回double类型的机器epsilon。
Python
1 | x = 3.14159 |
Python字符串格式化表达式,这段代码会输出
"3.1 3.14 3.141, 2.718"
{}
:这是一个占位符,它会被.format()方法中的参数替换。0
:这是格式说明符中的字段名,表示.format()方法中的第一个参数。如果.format()方法中有多个参数,你可以通过改变这个数字来选择不同的参数。:
:这是格式说明符的开始,它后面的内容用于控制参数的输出格式。.3
:这是精度,表示小数点后的位数。在这里,它设置精度为3,也就是小数点后有三位。f
:这是格式类型,表示浮点数。它会将参数转换为浮点数,并按照前面的精度输出。
1 | # worse |
1 | print(math.sin(math.radians(30))) |
在Python的math模块中,所有的三角函数(如sin、cos等)都接受的是弧度值,而不是角度值。所以,需要先要用
math.radians()
转换为弧度。
1 | arr = input() |
标准输入读取一行文本,然后将这行文本分割为多个字符串,再将这些字符串转换为整数,并将这些整数存储在一个列表中。
1 | print("ASCII value of 'A':", ord('A')) # Output: 65 |
A-Z: 65-90, a-z: 97-122
Others
gcd(a, b) = gcd(b, a % b)
基于欧几里得算法递归实现求两个整数的最大公约数
lcm(a, b) = a * b / gcd(a, b)
一个数的最小公倍数和最大公约数的乘积等于这两个数的乘积。
1 | find . -type f -exec sed -i 's#https://github.com/#https://mirror.ghproxy.com/github.com/#g' {} \; |
替换当前目录及其子目录中所有文件中的Github资源下载镜像地址
1 | find . -type f \( -name "*.cpp" -o -name "*.hpp" \) -exec sed -i 's/MW_LOG_I/MW_LOG_D/g' {} \; |
修改当前目录及其子目录中所有.cpp和.hpp文件中的log打印等级