1.auto
auto 可以在声明变量的时候根据变量初始值的类型自动为此变量选择匹配的类型,也就是说,声明时必须要赋予初值。
auto 自动类型推断发生在编译期间,属于编译器特性,不影响最终的机器码质量,不影响运行效率。
当有些类型名比较长(例如泛型)的时候,使用 auto 可以简化代码。
#include<iostream>
using namespace std;
int main()
{
auto bvalue = true; // bool
auto ch = 'a'; // char
auto dvalue = 1.2; // double
auto ivalue = 5; // int
return 0;
}
2.范围for语句
2.1 遍历数组
不用知道数组的大小即可方便地遍历数组。
举例1:
#include<iostream>
using namespace std;
int main()
{
int arr[]{ 12, 13, 14, 16, 18 };
// 把arr每个元素拷贝到x中,打印x值
for (auto x : arr)
{
cout << x << endl;
}
for (auto x : { 12, 13, 14, 16, 18 })
{
cout << x << endl;
}
return 0;
}
举例2:
#include<iostream>
using namespace std;
int main()
{
int arr[]{ 12, 13, 14, 16, 18 };
// 引用省了拷贝这个动作,提高了系统效率
for (auto &x : arr)
{
cout << x << endl;
}
return 0;
}
2.2 遍历字符串
#include<iostream>
#include<string>
using namespace std;
int main()
{
string str = "hello, world!";
for (auto ch : str)
{
cout << ch << endl;
}
return 0;
}
2.3 遍历STL容器
例1:遍历 vector,同时通过引用修改容器内容。
#include<iostream>
#include<string>
#include<vector>
using namespace std;
int main()
{
vector<string> str_vec = { "i", "like", "china" };
for (auto &it : str_vec)
{
it = "C++";
}
for (auto &it : str_vec)
{
cout << it << endl;
}
return 0;
}
例2:遍历 map,每次拿到的元素既不是键也不是值,而是由键和值组成的 pair。
#include<iostream>
#include<string>
#include<map>
using namespace std;
int main()
{
map<int, string> hash_map = { {1, "C++"}, {2, "Java"}, {3, "Python"} };
for (auto &it : hash_map)
{
cout << it.first << " " << it.second << endl;
}
return 0;
}
3.nullptr
nullptr 代表的是空指针,但是 NULL 和 nullptr 实际上是不同的类型。
#include <iostream>
using namespace std;
int main()
{
cout << typeid(NULL).name() << endl;
cout << typeid(nullptr).name() << endl;
return 0;
}
NULL 实际上就是 0
,使用 nullptr 能够避免在整数和指针之间发生混淆,解决 NULL 的二义性问题。
#include <iostream>
using namespace std;
void func(int v)
{
cout << "func(int) - " << v << endl;
}
void func(int* v)
{
cout << "func(int *) - " << v << endl;
}
int main()
{
func(NULL);
func(nullptr);
return 0;
}
结论:对于和指针有关的场合,能用 nullptr 的全部用 nullptr 取代 NULL。