c / c++programming languages

How to Implement the “some” Function in C++ using Templates?

The some function in Javascript takes one function callback and returns true if any element in the array passes the test i.e. the function returns true. For example:

1
2
3
4
ages = [3, 5, 18, 17, 20, 4];
if (ages.some(function(age){return age>=18;})) {
   console.log("We have grown-ups!");
}

In C/C++, you can use templates to define the prototype of the some function. You might also consider prototyping this in a C++ class.

1
2
3
4
5
6
7
8
9
10
// https://helloacm.com/how-to-implement-the-some-function-in-c-using-templates/
template <typename T>
bool some(T *data, int size, bool(*SOME_FUNC)(T element)) {
    for (int i = 0; i < size; ++ i) { // iterative each element
        if (SOME_FUNC(i)) { // test the element
            return true;
        }
    }
    return false;
}

However, we modifies the parameters a little bit because C/C++ is a static-type programming language and it does not support the extension method definition. The above JS example can then be illustrated in C++ (For Pure C, you need to change the bool type to int):

1
2
3
bool check_age(int age) {
    return age >= 18;
}

And here is how you use the ‘some’ function:

1
2
3
4
int ages[6] = { 3, 5, 18, 17, 20, 4 };
if (some<int>(arr, sizeof(arr)/sizeof(arr[0]), &check_age)) {
    std::cout << "We have grown-ups!";
}

Feature Comments

How about changing the parameters to const t& and use something like std::iterate, so we can pass any type of list (std::map, char* etc) and any type of function (boost::function, boost::bind, C/C++ static). And a lambda expression instead of check_age function ;)