AudioPlastic

C++11 Is Poetic

| Comments

I will start posting cool little blocks of code, like short poems when I see neat little things to do ..

Find multiples in a vector the C++11 way
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
#include <vector>
using namespace std;

int main ()
{
	vector<int> v{12,324,45,65,787,9}; //Uniform initialization
	cout << "In vector: ";
	for (auto val : v) {cout << val << ", ";} //Range based for
	int m = 5;
	cout<< "there are "
		<< count_if(v.begin(), v.end(), [m](int i){return i%m == 0;}) //lambdas
		<< " multiples of " << m << endl;
}

In vector: 12, 324, 45, 65, 787, 9, there are 2 multiples of 5

For some more depth on the functional goodness see this Dr. Dobbs article

Comments