Skip to content

Instantly share code, notes, and snippets.

@PhDP
Created January 29, 2015 19:07
Show Gist options
  • Save PhDP/24efc7521f811d27f680 to your computer and use it in GitHub Desktop.
Save PhDP/24efc7521f811d27f680 to your computer and use it in GitHub Desktop.
Loops / iterators in C++ (not tested)
// 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