序列for循环语句
序列for循環(huán)語句
序列for循環(huán)語句允許重復(fù)遍歷一組序列,而這組序列可以是任何可以重復(fù)遍歷的序列,如由begin()和end()函數(shù)定義的STL序列。所有的標(biāo)準(zhǔn)容器都可用作這種序列,同時(shí)它也同樣可以是std::string,初始化列表(list),數(shù)組,以及任何由begin()和end()函數(shù)定義的序列,例如輸入流。這里是一個(gè)序列for循環(huán)語句的例子:
void f(const vector& v){for (auto x : v) cout << x << ‘n’;for (auto& x : v) ++x; // 使用引用,方便我們修改容器中的數(shù)據(jù)}可以這樣理解這里的序列for循環(huán)語句,“對于v中的所有數(shù)據(jù)元素x”,循環(huán)由v.begin()開始,循環(huán)到v.end()結(jié)束。又如:
for (const auto x : { 1,2,3,5,8,13,21,34 })cout << x << ‘n’;begin()函數(shù)(包括end()函數(shù))可以是成員函數(shù)通過x.begin()方式調(diào)用,或者是獨(dú)立函數(shù)通過begin(x)方式調(diào)用。
(譯注:好像C#中早就有這種形式的for循環(huán)語句,用于遍歷一個(gè)容器中的所有數(shù)據(jù)很方便,難道C++是從C#中借用過來的?)
或參見:
- the C++ draft section 6.5.4 (note: changed not to use concepts)
- [N2243==07-0103] Thorsten Ottosen:
Wording for range-based for-loop (revision 2). - [N3257=11-0027 ] Jonathan Wakely and Bjarne Stroustrup:?Range-based for statements and ADL?(Option 5 was chosen).
轉(zhuǎn)載于:https://www.cnblogs.com/VindyLeong/p/4201673.html
總結(jié)
- 上一篇: vscode快捷替换json格式
- 下一篇: #Plugin 中国省市选择插件