I created 3 different implementations (which produce the same results) using the count_if
function from STL. I wish to check the number of elements in the vector which are strictly less than 6.
These are:
- C++ lambda function
- Global function (no functor)
- Using class and creating my own functor
These implementations work, but, how can I improve them into a more efficient and robust solutions?
#include <vector> #include <algorithm> #include <numeric> #include <functional> #include <iostream> using namespace std; // GLOBAL function (not FUNCTOR) See below for FUNCTOR implementation! template <int num> bool lessThan(int x) { return(x < num); // return TRUE if the value is less than NUM } // Paramterized Function with more robust FUNCTOR implementation (written by me) (I know stl has this built in) class LessThan { private: int m_x; // the value we wish to be less than public: LessThan(int val) : m_x(val) {} // custom constructor: assign a value to x bool operator() (int upper) // all values must be strictly less than the upper bound { return (m_x < upper); } }; int main() { vector<int> vec = { 2, 7, 4, 5, 7, 7}; // Using new C++ Lambda function implementation int x = count_if(vec.begin(), vec.end(), [](int x) {return x < 6; }); // using C++ Lambda Function (just a function with no name) cout <<"There exists " << x << " integers in vec which are strictly less than 6." << endl; // Using global lessThan6 implementation (NOT FUNCTOR) int y = count_if(vec.begin(), vec.end(), lessThan<6>); // not very robust cout << "There exists " << y << " integers in vec which are strictly less than 6." << endl; // Using MY OWN FUNCTOR implementation int z = count_if(vec.begin(), vec.end(), LessThan(6)); // robust cout << "There exists " << z << " integers in vec which are strictly less than 6." << endl; }