范围for循环
范围for循环(Range-based for loop)是 C++11 引入的一种简洁的循环语法,用于遍历容器中的元素或者其他支持迭代的数据结构。
范围for循环可以让代码更加简洁和易读,避免了传统for循环中索引的操作。
下面是范围for循环的基本语法:
cpp
for (const auto &element : container) {
// 对 element 进行操作
}
container 是一个可以被迭代的对象,比如数组、容器(如 vector、list、set 等)、字符串等。
element 是容器中的每个元素,在循环的每次迭代中都会被赋值为容器中的一个元素,而且是以 const auto & 的形式引用该元素,可以避免不必要的拷贝。
c
#include <iostream>
#include <vector>
using namespace std;
int main(void)
{
vector<int> t{ 1,2,3,4,5,6 };
for (auto value : t) //for (const auto &value : vec)
{
cout << value << " ";
}
cout << endl;
return 0;
}
在for循环内部声明一个变量的引用就可以修改遍历的表达式中的元素的值,但是这并不适用于所有的情况,对应set容器来说,内部元素都是只读的,这是由容器的特性决定的,因此在for循环中auto&会被视为const auto & 。
using的使用
- 使用 using 定义别名:
c
//using 新的类型 = 旧的类型;
using MyInt = int;
//定义函数指针
// 使用typedef定义函数指针
typedef int(*func_ptr)(int, double);
// 使用using定义函数指针
using func_ptr1 = int(*)(int, double);