logical_and Predicate Function in C++

This C++ program demonstrates the logical_and() algorithm. The program uses transform function from algorithm library to compute the logical_and of corresponding elements of two vectors by passing logical_and as the binary predicate. The result is stored in the first vector itself.

Here is the source code of the C++ program which demonstrates the logical_and() algorithm. The C++ program is successfully compiled and run on a Linux system. The program output is also shown below.

  1. /*
  2.  * C++ Program to demonstrate usage of logical_and predicate
  3.  */
  4. #include <iostream>
  5. #include <algorithm>
  6. #include <vector>
  7. #include <functional>
  8. using namespace std;
  9.  
  10. void print(const vector <int>& v)
  11. {
  12.     vector <int>::const_iterator i;
  13.     for(i = v.begin(); i != v.end(); i++)
  14.     {
  15.         cout << *i << " ";
  16.     }
  17.     cout << endl;
  18. }
  19.  
  20. int main()
  21. {
  22.     vector <int> a(10), b(10);
  23.  
  24.     for (int i = 0; i < 10 ;i++)
  25.     {
  26.         a[i] = i % 2;
  27.         b[i] = i % 4;
  28.     }
  29.     cout << "Vector a : ";
  30.     print(a);
  31.     cout << "Vector b : ";
  32.     print(b);
  33.     // Save the result in vector a
  34.     transform(a.begin(), a.end(), b.begin(), a.begin(), logical_and <int>());
  35.     cout << "a AND b  : ";
  36.     print(a);
  37. }

$ a.out
Vector a : 0 1 0 1 0 1 0 1 0 1 
Vector b : 0 1 2 3 0 1 2 3 0 1 
a AND b  : 0 1 0 1 0 1 0 1 0 1

Sanfoundry Global Education & Learning Series – 1000 C++ Programs.

advertisement
advertisement
If you wish to look at all C++ Programming examples, go to C++ Programs.

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.