Transform deque with boolean function : transform « deque « C++ Tutorial






#include <algorithm>
#include <deque>
#include <iostream>

using namespace std;

bool logical_xor( bool a, bool b );

void print_result( const char* names[], const deque<bool>& print,const char* text );

int main( )
{
   const char* contacts[] ={ "A", "J","S", "D", "R" };
   const bool salesman1_data[] = { true, true, false, false, true };
   const bool salesman2_data[] = { false, false, true, true, true };
   const int num_customers = sizeof( salesman1_data ) / sizeof( salesman1_data[0] );

   // create deques and initialize with above data
   deque<bool> salesman1( salesman1_data,salesman1_data+num_customers );
   deque<bool> salesman2( salesman2_data,salesman2_data+num_customers );
   deque<bool> result( num_customers );

   print_result( contacts, salesman1,"has been called by Salesman 1" );
   print_result( contacts, salesman2,"has been called by Salesman 2" );

   // customers called by both salesmen
   transform( salesman1.begin(), salesman1.end(), salesman2.begin(),result.begin(), logical_and<bool>() );
   print_result( contacts, result,"has been called by both salesmen" );

   // customers called by at least one salesman
   transform( salesman1.begin(), salesman1.end(), salesman2.begin(),result.begin(), logical_or<bool>() );
   print_result( contacts, result,"has been called by at least one salesman" );

   // customers called by only one salesman
   transform( salesman1.begin(), salesman1.end(), salesman2.begin(),result.begin(), logical_xor );
   print_result( contacts, result,"has been called by only one salesman" );

   // customers not called by Salesman 1
   transform( salesman1.begin(), salesman1.end(),result.begin(), logical_not<bool>() );
   print_result( contacts, result,"has not been called by Salesman 1" );
}

inline
bool logical_xor( bool a, bool b ) {  
   return a ? !b : b;  
}
void print_result( const char* names[], const deque<bool>& which,const char* text ){
   for( deque<bool>::size_type i = 0; i < which.size(); ++i )
      if( which[i] )
         cout << names[i] << " " << text << endl;
   cout << endl;
}








22.12.transform
22.12.1.Transform deque with boolean function
22.12.2.Checking if One Container Is Less Than or Greater Than Another