一、基于范围for循环
在C/C++中经常需要遍历数组做某些事情,数组的遍历边界由程序员自己控制,经常有人粗心导致数组越界。并且遍历写起来比较繁琐
1 2 3 4 5
| int arr[] = { 1,2,3,4,5,6,7,8,9,10}; for (int i = 0; i < sizeof(arr) / sizeof(arr[0]); i++) { cout << arr[i] << endl; }
|
C++11中引入了基于范围的for循环。for循环后的括号由冒号“ :”分为两部分:第一部分是范围内用于迭代的变量,第二部分则表示被迭代的对象。由于不知道被迭代对象的元素是什么类型,我们可以使用auto。
1.1 遍历对象
遍历对象有两种方式,方式一:将对象中每个元素值拷贝到迭代的变量中,方式二:使用引用,迭代的变量就是对象元素的引用,推荐方式二
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
| #include <iostream>
using namespace std;
int main() { int arr[] = { 1,2,3,4,5}; for (int i = 0; i < 5; i++) { cout << &arr[i] << endl; }
for (auto e : arr) { cout << "&e = " << &e << endl; cout << e << endl; }
for (auto& e : arr) { cout << "&e = " << &e << endl; cout << e << endl; } }
|
输出
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| 009FF958 009FF95C 009FF960 009FF964 009FF968 &e = 009FF91C 1 &e = 009FF91C 2 &e = 009FF91C 3 &e = 009FF91C 4 &e = 009FF91C 5 &e = 009FF958 1 &e = 009FF95C 2 &e = 009FF960 3 &e = 009FF964 4 &e = 009FF968 5
|
1.2 修改对象
由于要修改对象中每个元素,只能使用引用方式
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| #include <iostream>
using namespace std;
int main() { int arr[] = { 1,2,3,4,5}; for (auto& e : arr) { e = e + 10; } for (auto& e : arr) { cout << e << endl; } }
|
输出
1.3 范围for限制条件
范围for迭代的对象范围必须是确定的,下面这种使用是错误的
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| void print(int arr[]) { for(auto& elem : arr) { cout << elem; } cout << endl; }
int main() { int arr[5] = {1,2,3,4,5}; print(arr); return 0; }
|
二、nullptr
C/C++中指针让我们可以随心所欲的操作数据,但也带来了许多陷阱。在C语言中对于一个指针变量不用时让它指向NULL。但在C++中却不能这样,因为NULL本质是一个宏,C和C++对NULL宏定义不同
1 2 3 4 5 6 7
| #ifndef NULL #ifdef __cplusplus #define NULL 0 #else #define NULL ((void *)0) #endif #endif
|
可以看出在C语言中,NULL被定义为((void *)0),类型为指针.而在C++中被定为0,类型为int。C++11 引入关键字nullptr用来定义空指针
1 2 3 4
| int* p = nullptr; int* p = ((void *)0); int* p = ((void *)NULL);
|