范圍for循環
范圍for循環(Range-based for loop)是 C++11 引入的一種簡潔的循環語法,用于遍歷容器中的元素或者其他支持迭代的數據結構。
范圍for循環可以讓代碼更加簡潔和易讀,避免了傳統for循環中索引的操作。
下面是范圍for循環的基本語法:
for (const auto &element : container) {// 對 element 進行操作
}
container 是一個可以被迭代的對象,比如數組、容器(如 vector、list、set 等)、字符串等。
element 是容器中的每個元素,在循環的每次迭代中都會被賦值為容器中的一個元素,而且是以 const auto & 的形式引用該元素,可以避免不必要的拷貝。
#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 定義別名:
//using 新的類型 = 舊的類型;
using MyInt = int;//定義函數指針
// 使用typedef定義函數指針
typedef int(*func_ptr)(int, double);// 使用using定義函數指針
using func_ptr1 = int(*)(int, double);