1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
|
#include <iostream>
#include <vector>
#include <fstream>
#include <algorithm>
#include <iterator>
std::ostream& copy_even( const std::vector<int>& vec, std::ostream& stm )
{
// http://www.stroustrup.com/C++11FAQ.html#lambda
static const auto is_even = [] ( int v ) { return v%2 == 0 ; } ;
std::copy_if( vec.begin(), vec.end(), std::ostream_iterator<int>( stm, " " ), is_even ) ;
return stm ;
}
int main()
{
const std::vector<int> numbers { 0, 5, 8, 2, 3, 7, 6, 4, 9, 2, 5, 6, 7, 4, 4, 7, 2, 5 } ;
copy_even( numbers, std::cout ) << '\n' ; // copy even numbers to stdout
std::ofstream file( "even.txt" ) ;
copy_even( numbers, file << "the numbers written to file are: " ) << '\n' ; // copy even numbers to file
}
| |