版本比较
论C++中的神奇语法
正文
增加 76 行删除 4 行
14 行未改动151617181920192021222324252425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910014 行未改动
另一种方式就是换行不用`endl`,用`\n`
代码示范:```cpp#include<bits/stdc++.h>```cpp line-numbers lines=4-6#include<iostream>
int main(){ std::ios::sync_with_stdio(false); cin.tie(nullptr); std::cout << "Hello World" << std::endl; cin.tie(nullptr);//如果是C++98,用NULL代替nullptr std::cout << "Hello World" << '\n'; return 0;}```## 2.获取线性数组长度大家熟知的sizeof**关键字**(不是函数)可以获取一个数组、vector、pair等。
但是这个关键字返回值是一个占用内存多少byte,需要大家手动去除一下。
下面给出各种数据类型的占用byte:::info[各种数据类型占用byte]|数据类型|占用byte||---|---||int|4||float|4||double|8||long long|8||char|1||bool|1||short|2|:::程序示范:
```cpp line-numbers#include<bits/stdc++.h>
using namespace std;int a[]={1,1,4,5,1,4};//定义一个数组vector<int>v={1,1,4,5,1,4};int main(){ cout << sizeof v/sizeof int << endl; return 0;}```## 3.for循环的自动推导for循环支持自动推导vector,数组,字符串,列表等
代码格式如下:```cppfor(自动推导变量 : 可遍历容器/数组/初始化列表){ // 循环体}```
```cpp line-numbers#include<iostream>#include<algorithm>#include<string>using namespace std;//数据定义在下方,注意先后顺序string s="__ZhangHuiyi__";//函数定义在下方,注意顺序,如有冲突,建议先集体声明
int main(){ for(char c:s){ cout<<s; } return 0;}//该程序输出了__ZhangHuiyi__```## 4.如何使用两个变量进行交换本算法使用C++的**位运算**,进行巧妙计算。```cpp line-numbers#include<iostream>using namespace std;int main(){ int a,b; cin>>a>>b; a=a^b; b=a^b; a=a^b; cout<<a<<' '<<b<<endl; return 0;}```