Python's any and all in C++

When working on some Project Euler problems with a friend, he used a handy little Python trick called all. Here is a typical use of all:

if all([x > 1 for key in some_list]):
   print 'True'  

Simply put, if every element of some_list is greater than 1, then true is returned. Similarly, there is another function called any which returns true is any element in a list is true. I decided to test out my C++ skills and write this. Here is my attempt.

template<class InputIterator, class UnaryFunction>
   bool all(InputIterator first, InputIterator last, UnaryFunction f) {
   bool allTrue;
   for(allTrue = true; first != last; ++first) {
      if(f(*first) == false) {
         allTrue = false;
         break;
      }
   }
   return allTrue;
}
  
template<class InputIterator, class UnaryFunction>
   bool any(InputIterator first, InputIterator last, UnaryFunction f) {
   bool anyTrue;
   for(anyTrue = false; first != last; ++first) {
      if(f(*first) == true) {
         anyTrue = true;
         break;
      }
   }
   return anyTrue;
}

Now to use these functions, simply use it like any other STL function. Make a function or functor that takes the type of the list, and pass it to the any or all function.

struct apply {
   bool operator() (int x) {
      if(x > 1) {
         return true;
      }
      return false;
   } 
};  

And now we just use it like you would expect.

int main() {  
   std::vector<int> integers;

   integers.push_back(0);
   integers.push_back(1);
   integers.push_back(2);
   integers.push_back(3);
   bool result = all(integers.begin(), integers.end(), apply());
   std::cout << "Result is: " << result << std::endl;
   result = any(integers.begin(), integers.end(), apply());
   std::cout << "Result is: " << result << std::endl;
   return 0;
 }  

Please give me your comments on what you think.
Post a Comment