C++11之基于范围的for循环
采用c++11新特性中的基于范圍for循環(huán),不必去操心數(shù)組越界(邊界)問題,因此非常的方便,特別是在項(xiàng)目開發(fā)中。
語法形式:
for(declaration:expression)
{statement
}
其中:expression部分表示一個(gè)對(duì)象,用于表示一個(gè)序列。declaration部分負(fù)責(zé)定義一個(gè)變量,該變量將被用于訪問序列中的基礎(chǔ)元素。
每次迭代,declaration部分的變量會(huì)被初始化為expression部分的下一個(gè)
元素值。
示例1:
#include<iostream>
#include<stdlib.h>
#include<string>
using namespace std;
int main()
{int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };for (auto val : arr){cout << val << " ";}system("pause");return 0;
}輸出結(jié)果:
1 2 3 4 5 6 7 8 9 10
示例2:
若迭代器變量的值希望能夠在for中被修改,可以采用引用&的方式;
#include<iostream>
#include<stdlib.h>
#include<string>
using namespace std;
int main()
{int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };for (auto &val : arr){if (val == 5){val += 1;}cout << val << " ";}system("pause");return 0;
}輸出結(jié)果:
1 2 3 4 5 6 6 7 8 9 10
示例3:
對(duì)于STL標(biāo)準(zhǔn)模板庫也同樣適用。
#include<iostream>
#include<stdlib.h>
#include<string>
#include<vector>
using namespace std;
int main()
{vector<int> arr;arr.push_back(1);arr.push_back(3);arr.push_back(5);arr.push_back(7);arr.push_back(9);for (auto &val : arr){cout << val << " ";}system("pause");return 0;
}輸出結(jié)果:
1 3 5 7 9
示例4.
#include<iostream>
#include<stdlib.h>
#include<string>
#include<map>
using namespace std;
int main()
{map<int, string> arr;arr.insert(pair<int, string>(1, "hello"));arr.insert(pair<int, string>(2, "world."));for (auto &val : arr){cout << val.first << "," << val.second << endl;}system("pause");return 0;
}輸出結(jié)果:
1,hello
2,world.
在編寫的c++程序中,如果是窗口,有時(shí)會(huì)一閃就消失了,如果不想讓其消失,在程序中添加:
system("pause");
注意:不要再return 的語句之后加,那樣就執(zhí)行不到了。
2.基于范圍的for循環(huán)特點(diǎn)
(1)和普通循環(huán)一樣,也可以采用continue跳出循環(huán)的本次迭代。
(2)用break來終止整個(gè)循環(huán)
3.基于范圍的for循環(huán)使用的要求及依賴條件
(1)for循環(huán)迭代的范圍是可以確定的;如數(shù)組的第一個(gè)元素和最后一個(gè)元素便構(gòu)成了for選好的迭代范圍。
(2)對(duì)于用戶自定義的類,若類中定義便實(shí)現(xiàn)的有begin、end函數(shù),則這個(gè)begin、end便是for循環(huán)的迭代范圍。
(3)基于范圍的for循環(huán)要求迭代器的對(duì)象實(shí)現(xiàn):++ ==等操作符。
(4)對(duì)于STL標(biāo)準(zhǔn)模板庫中(如:vector,set,list,map,queue,deque,string等)的各種容器使用“基于范圍的for循環(huán)”是不會(huì)有
任何問題的,因?yàn)檫@些容器中都定義了相關(guān)操作。
?
總結(jié)
以上是生活随笔為你收集整理的C++11之基于范围的for循环的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 蒙特卡洛方法的实例
- 下一篇: C++11之final关键字