写法技巧
1、for循环中的技巧
- i>=0的写法可以写作~i,因为当-1的二进制表示全是1,取反之后就是0,会终止循环。
for(int i=30;~i;--i)
{
...
}
- 字符串中最后一位是/0可以作为终止条件
for(int i=0;str[i];++i)
{
...
}
- 在java中有for-each的写法,可称为加强for循环
for(int i:a){
System.out.println(i);
}
2、引用&的用法
- 可以利用&起别名
int b=0;
cout<<b;//b=0
int &a=b;
a=2;
cout<<b;//b=2
3、输入输出优化
- 加上这段代码可以进行优化,但是scanf和cin等就不能混用了,具体见优化
#include <iostream>
int main() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
...
}
- O2优化,原理见O1、O2、O3优化原理
#pragma GCC optimize(2)
4、生成随机数
shuffle(nums.begin(), nums.end(), mt19937(random_device{}()))
5、按位运算的注意事项
double和float数据类型是无法进行按位运算的,因为电脑内部是按照符号位、指数位和真数进行存储的,所以单纯按照位运算是会出现问题的。
6、重载运算符
例如加减法总是用在数字的运算上面,但是如果我想要用在某个自定义的类上面做加法,就需要用到重载运算符的做法了。例子如下:
#include <iostream>
using namespace std;
class Box
{
private:
double length; // 长度
double breadth; // 宽度
double height; // 高度
public:
Box(double length,double breadth,double height)
{
this.length=length;
this.breadth=breadth;
this.height=height;
}
// 重载 + 运算符,用于把两个 Box 对象相加
Box operator+(const Box& b)
{
Box box;
box.length = this->length + b.length;
box.breadth = this->breadth + b.breadth;
box.height = this->height + b.height;
return box;
}
};
int main()
{
Box box1=new Box(1,2,3);
Box box2=new Box(4,5,6);
Box box3=box1+box2;
}
重载运算符的写法是固定的,都是operate关键词加运算符号有些符号是不能进行重载的,需要注意。
7、sort函数中的比较函数
我之前总以为sort函数中的排序函数是个重载,没想到它是可以自己重写的
struct node{
int a;
int b;
}s[100];
bool cmp(const node &x,const node &y)//注意是bool类型的
{
return x.b>y.b;
}
int main()
{
sort(s+1,s+50,cmp);//造成的效果就是以b为判定条件从大到小排序。
}
8、模板template的使用
模板有函数模板和类模板,他可以指定任意的数据类型,所以在定义的时候就起到了一劳永逸的效果
template<typename T>
void fun(T& t1, T& t2) {
T tmpT;
tmpT = t1;
t1 = t2;
t2 = tmpT;
}
int main()
{
string a="1",b="2";
int c=1,d=2;
fun(a,b);
fun(c,d);
return 0;
}
9、c++strcut结构体中可以定义构造函数
//以链表的遍历为例子
#include <bits/stdc++.h>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode() : val(0), next(NULL) {}
ListNode(int x) : val(x), next(NULL) {}
ListNode(int x, ListNode *next) : val(x), next(next) {}
};
int main()
{
ListNode* node1=new ListNode(1);
ListNode* node2=new ListNode(2);
ListNode* node3=new ListNode(3);;
ListNode* node4=new ListNode(4);
ListNode* node5=new ListNode(5);
node1->next=node2;
node2->next=node3;
node3->next=node4;
node4->next=node5;
ListNode* t=node1;
while(t!=NULL)
{
cout<<t->val<<" ";
t=t->next;
}
return 0;
}