Last active
November 26, 2016 18:54
-
-
Save illescasDaniel/d11aafa6354a6e71c1ce6c57e86121bd to your computer and use it in GitHub Desktop.
For loops [C++]
This file contains 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
#include <iostream> | |
#include <vector> | |
#include <algorithm> | |
using namespace std; | |
void print(const int& i) { | |
cout << i << ' '; | |
} | |
int main() { | |
vector<int> numbers = {1,2,3,4}; | |
// Classic for loop | |
for (int i = 0; i < numbers.size(); i++) { | |
cout << numbers[i] << ' '; | |
} | |
cout << endl; | |
// For with iterators | |
for (vector<int>::iterator it = numbers.begin(); it != numbers.end(); ++it) { | |
cout << *it << ' '; | |
} | |
cout << endl; | |
// Range-based for loop (since C++11) (similar to Janumbersa) | |
for (const int& number: numbers) { | |
cout << number << ' '; | |
} | |
cout << endl; | |
/* FOR_EACH - Applies a function to a range of elements */ | |
for_each(numbers.begin(), numbers.end(), print); | |
cout << endl; | |
// You can use lambda functions too | |
for_each(numbers.begin(), numbers.end(), [](const int& i){ cout << i << ' '; }); | |
// Alternative for_each with boost::lambda | |
// for_each(numbers.begin(), numbers.end(), cout << _1 << ' '); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment