Created
November 8, 2012 06:45
-
-
Save juehan/4037272 to your computer and use it in GitHub Desktop.
C++11 Range Based for loop
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| //Range Based For Loop Example (Run on VS2012) | |
| #include <iostream> | |
| #include <vector> | |
| #include <algorithm> | |
| template <typename T> | |
| void printElement1(const T& collection) | |
| { | |
| std::cout<<"printElement using traditional for loop"<<std::endl; | |
| for(auto it = begin(collection); it != end(collection); ++it) | |
| { | |
| std::cout<<*it<<" "; | |
| } | |
| std::cout<<std::endl; | |
| } | |
| template<typename T> | |
| void printElement2(const T& collection) | |
| { | |
| std::cout<<"printElement using ranged for loop"<<std::endl; | |
| for(auto it : collection) | |
| { | |
| std::cout<<it<<" "; //be noted not used *it | |
| } | |
| std::cout<<std::endl; | |
| } | |
| int main() | |
| { | |
| //initialize vector | |
| std::vector<int> vArr(10); | |
| int i = 0; | |
| std::generate(vArr.begin(), vArr.end(), [&i]{ | |
| return i++; | |
| }); | |
| //print out | |
| printElement1(vArr); | |
| printElement2(vArr); | |
| //update items inside | |
| for(int& i : vArr) | |
| { | |
| i *= 2; | |
| } | |
| std::cout << "----- Update Items Inside -----" << std::endl; | |
| //print out | |
| printElement1(vArr); | |
| printElement2(vArr); | |
| } | |
| /* | |
| output | |
| printElement using traditional for loop | |
| 0 1 2 3 4 5 6 7 8 9 | |
| printElement using ranged for loop | |
| 0 1 2 3 4 5 6 7 8 9 | |
| ----- Update Items Inside ----- | |
| printElement using traditional for loop | |
| 0 2 4 6 8 10 12 14 16 18 | |
| printElement using ranged for loop | |
| 0 2 4 6 8 10 12 14 16 18 | |
| Press any key to continue . . . | |
| */ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment