C++: Filter

Bjarne-stroustrup
 

Select certain elements from an Array into a new Array in a generic way. To demonstrate, select all even numbers from an Array.

As an option, give a second solution which filters destructively, by modifying the original Array rather than creating a new Array.

#include <vector>
#include <algorithm>
#include <functional>
#include <iterator>
#include <iostream>

int main() {
	std::vector<int> ary;
	for (int i = 0; i < 10; i++)
	ary.push_back(i);
	std::vector<int> evens;
	std::remove_copy_if(ary.begin(), ary.end(), back_inserter(evens),
			std::bind2nd(std::modulus<int>(), 2)); // filter copy
	std::copy(evens.begin(), evens.end(),
	std::ostream_iterator<int>(std::cout, "\n"));

	return 0;
}

Works with: C++11

#include <vector>
#include <algorithm>
#include <iterator>
#include <iostream>

using namespace std;

int main() {
	vector<int> ary = {1, 2, 3, 4, 5, 6, 7, 8, 9};
	vector<int> evens;

	copy_if(ary.begin(), ary.end(), back_inserter(evens),
			[](int i) { return i % 2 == 0; });

	// print result
	copy(evens.begin(), evens.end(), ostream_iterator<int>(cout, "\n"));
}

SOURCE

Content is available under GNU Free Documentation License 1.2.