C++ 11 基於範圍的for迴圈
阿新 • • 發佈:2019-01-10
基於範圍的for迴圈:
對於內建陣列以及包含方法begin()和end()的類(如std::string)和STL容器,基於範圍的for迴圈可以簡化為他們編寫迴圈的工作。這種迴圈對陣列或容器中的每個元素執行指定的操作:
#include <iostream>
int main()
{
double prices[5] = {4.99,10.99,6.87,7.99,8.49};
for (double x : prices)
std::cout << x << std::endl;
return 0;
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
其中,x將依次為prices中每個元素的值。x的型別應與陣列元素的型別匹配。 一種更容易更安全的方式是,使用auto來宣告x,這樣編譯器將根據prices宣告的資訊來推斷x的型別:
for (auto x : prices)
std::cout << x << std::endl;
- 1
- 2
如果要在迴圈中修改陣列或容器的每個元素,可使用引用型別:
std ::vector<int> vi(6);
for (auto &x : vi)
x = std::rand();
- 1
- 2
- 3
基於範圍的for迴圈:
對於內建陣列以及包含方法begin()和end()的類(如std::string)和STL容器,基於範圍的for迴圈可以簡化為他們編寫迴圈的工作。這種迴圈對陣列或容器中的每個元素執行指定的操作:
#include <iostream>
int main()
{
double prices[5] = {4.99,10.99 ,6.87,7.99,8.49};
for (double x : prices)
std::cout << x << std::endl;
return 0;
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
其中,x將依次為prices中每個元素的值。x的型別應與陣列元素的型別匹配。 一種更容易更安全的方式是,使用auto來宣告x,這樣編譯器將根據prices宣告的資訊來推斷x的型別:
for (auto x : prices)
std::cout << x << std::endl;
- 1
- 2
如果要在迴圈中修改陣列或容器的每個元素,可使用引用型別:
std::vector<int> vi(6);
for (auto &x : vi)
x = std::rand();
- 1
- 2
- 3