Skip to main content
3 of 7
deleted 267 characters in body
Pii
  • 283
  • 1
  • 7

Using STL built-in functor notation

I created 4 different implementations (which should 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:

  1. C++ lambda function
  2. Global function (no functor)
  3. Using class and creating my own functor
  4. Built in STL functor

The first 3 implementations work; however, the 4th implementation gives me an error: "terms does not evaluate to a function taking 1 argument". How can I implement using the 4th technique for a more efficient and robust implementation.

#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;


}
Pii
  • 283
  • 1
  • 7