日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > c/c++ >内容正文

c/c++

[C++11]基于范围的for循环

發布時間:2023/12/4 c/c++ 23 豆豆
生活随笔 收集整理的這篇文章主要介紹了 [C++11]基于范围的for循环 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

C++11提供了一種新型的for循環形式 - 基于范圍的for循環

語法:

for (declaration : expression) {//循環體 }

在上面的語法格式中,declaration表示遍歷聲明,在遍歷過程中,當前被遍歷到的元素會被存儲到聲明的變量中,expression是要遍歷的對象,它可以是表達式,容器,數組,初始化列表等。

代碼如下:

#include <vector> #include <iostream> using namespace std;int main() {vector<int> v{ 1,2,3,4,5,6,7,8,9 };for (auto it = v.begin(); it != v.end(); it++){cout << *it << " ";}cout << endl;for (auto &item : v)//在這里使用了引用,這樣就不會拷貝,效率更高,還能修改元素的值{cout << item++ << " ";}cout << endl;for (auto &item : v){cout << item << " ";}cout << endl;for (const auto &item : v)//既提高效率,也不修改值{cout << item << " ";}cout << endl;return 0; }

測試結果:

基于范圍的for循環需要注意的3個細節:

1.關系型容器

代碼如下:

#include<iostream> #include <map> #include <string> using namespace std;int main() {map<int, string> mp{ {12, "Tom"}, { 13,"jack" }, { 33,"mike" }};for (const auto & item : mp){cout << item.first << " " << item.second << endl;}cout << "-----------------------" << endl;for (auto it = mp.begin(); it != mp.end(); it++){cout << it->first << " " << it->second << endl;}return 0; }

在上面的例子中使用了兩種方法對map容器進行遍歷,通過對比,有兩點需要注意:

測試結果:

2.元素只讀

代碼如下:

#include <iostream> #include <set>using namespace std;int main() {set<int>st{ 1,2,3,4,5,6 };for (auto &item : st){cout << item++ << endl;//error,不能給常量賦值}return 0; }

代碼如下:

#include <iostream> #include<map> #include <string>using namespace std;int main() {map<int, string>m{ {12,"Tom"},{14,"jack"},{19,"bom"} };for (auto & item : m){cout << item.first++ << " " << item.second << endl;//error}return 0; }

3.訪問次數

代碼如下:

#include <iostream> #include <vector> #include <string>using namespace std;vector<int>v{ 1,2,3,4,5,6 };vector<int>& getRange() {cout << "get vector range ..." << endl;return v; }int main() {for (auto val : getRange()){cout << val << " ";}cout << endl;return 0; }

測試結果:

總結

以上是生活随笔為你收集整理的[C++11]基于范围的for循环的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。