Created
January 29, 2015 19:07
-
-
Save PhDP/24efc7521f811d27f680 to your computer and use it in GitHub Desktop.
Loops / iterators in C++ (not tested)
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
// Compile with the -std=c++0x or -std=c++11 flag | |
#include <iostream> | |
#include <set> | |
#include <algorithm> | |
int main() { | |
// Create a set of numbers with the new initializer: | |
std::set<int> xs{ 6, 42, 47 }; | |
// Sum with iterators: | |
int sum0 = 0; | |
for (const auto &x : xs) | |
sum0 += x; | |
// "Functional" sum with <algorithm>: | |
const int sum1 = std::accumulate(xs.begin(), xs.end(), 0); | |
std::cout << "Sum0: " << sum0 << std::endl; | |
std::cout << "Sum1: " << sum1 << std::endl; | |
return 0; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment