1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
|
#include <iostream>
#include <map>
#include <algorithm>
int main()
{
const std::map<int, int> monthlengths{ {1,31}, {2,28}, {3,31}, {4,31},{5,31},{6,30},
{7,31}, {8,31}, {9,30}, {10,31}, {11,30}, {12,31} };
const int length = 30 ;
{
std::size_t cnt = 0 ;
for( const auto& pair : monthlengths ) if( pair.second > length ) ++cnt ;
std::cout << cnt << '\n' ;
}
{
#if __cplusplus >= 201402L // C++14 or later
std::cout << std::count_if( std::begin(monthlengths), std::end(monthlengths),
[length] ( const auto& pair ) { return pair.second > length ; } ) << '\n' ;
#else
std::clog << "this compiler does not conform to C++14\n" ;
#endif // __cplusplus
}
{
using const_reference = decltype(monthlengths)::const_reference ;
std::cout << std::count_if( std::begin(monthlengths), std::end(monthlengths),
[length] ( const_reference pair ) { return pair.second > length ; } ) << '\n' ;
}
{
using const_reference = std::map<int,int>::const_reference ;
std::cout << std::count_if( std::begin(monthlengths), std::end(monthlengths),
[length] ( const_reference pair ) { return pair.second > length ; } ) << '\n' ;
}
{
using value_type = decltype(monthlengths)::value_type ;
std::cout << std::count_if( std::begin(monthlengths), std::end(monthlengths),
[length] ( const value_type& pair ) { return pair.second > length ; } ) << '\n' ;
}
{
using value_type = std::map<int,int>::value_type ;
std::cout << std::count_if( std::begin(monthlengths), std::end(monthlengths),
[length] ( const value_type& pair ) { return pair.second > length ; } ) << '\n' ;
}
{
using value_type = decltype( *monthlengths.cbegin() ) ; // const_reference
std::cout << std::count_if( std::begin(monthlengths), std::end(monthlengths),
[length] ( value_type pair ) { return pair.second > length ; } ) << '\n' ;
}
{
using value_type = std::pair< const std::map<int,int>::key_type, std::map<int,int>::mapped_type > ;
std::cout << std::count_if( std::begin(monthlengths), std::end(monthlengths),
[length] ( const value_type& pair ) { return pair.second > length ; } ) << '\n' ;
}
{
using value_type = std::pair< const int, int > ;
std::cout << std::count_if( std::begin(monthlengths), std::end(monthlengths),
[length] ( const value_type& pair ) { return pair.second > length ; } ) << '\n' ;
}
{
using value_type = std::pair<int,int> ; // *** if we are going to do this, we should pass by value
// (semantically, a copy of the pair has to be made anyway)
std::cout << std::count_if( std::begin(monthlengths), std::end(monthlengths),
[length] ( value_type pair ) { return pair.second > length ; } ) << '\n' ;
}
}
|