一、基于范围for循环
在C/C++中经常需要遍历数组做某些事情,数组的遍历边界由程序员自己控制,经常有人粗心导致数组越界。并且遍历写起来比较繁琐
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 遍历对象
遍历对象有两种方式,方式一:将对象中每个元素值拷贝到迭代的变量中,方式二:使用引用,迭代的变量就是对象元素的引用,推荐方式二
#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;
}
// 每次循环读取数组元素值并赋值给临时变量e中,对e打印,e的生命周期是循环结束才销毁
for (auto e : arr)
{
cout << "&e = " << &e << endl;
cout << e << endl;
}
// 每次循环引用对应数组元素,e的生命周期是单次循环后销毁
for (auto& e : arr)
{
cout << "&e = " << &e << endl;
cout << e << endl;
}
}
输出
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 修改对象
由于要修改对象中每个元素,只能使用引用方式
#include <iostream>
using namespace std;
int main()
{
int arr[] = { 1,2,3,4,5};
for (auto& e : arr) // 每次循环e引用对应数组元素,e的生命周期是单次循环后销毁
{
e = e + 10;
}
for (auto& e : arr)
{
cout << e << endl;
}
}
输出
11
12
13
14
15
1.3 范围for限制条件
范围for迭代的对象范围必须是确定的,下面这种使用是错误的
void print(int arr[]) // 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宏定义不同
#ifndef NULL
#ifdef __cplusplus
#define NULL 0
#else
#define NULL ((void *)0)
#endif
#endif
可以看出在C语言中,NULL被定义为((void *)0)
,类型为指针.而在C++中被定为0
,类型为int。C++11 引入关键字nullptr
用来定义空指针
// 在C++11 中定义空指针方法
int* p = nullptr; // 推荐方式
int* p = ((void *)0);
int* p = ((void *)NULL);