Search code examples
c++stl-algorithm

C++ apply standard library algorithms to functions


Is there a way to apply non-modifying standard library algorithms to discrete functions instead of containers?

For example, consider the following function

int sqr(int i)
{
    return i*i;
}

How can I use std::find or std::lower_bound to search for the value 49, i.e. the algorithm should return 7? The easiest way would be to put the returns into a vector and apply the algorithm to the vector -- but this is obviously inefficient.


Solution

  • Hypothetically, you could use something like boost::iterator::counting_iterator. E.g., the following finds that 4 is the number whose square is 16:

    #include <algorithm>                                                                                                                                                                                         
    #include <iostream>
    
    #include <boost/iterator/counting_iterator.hpp>
    
    
    using namespace std;
    
    
    int main(int, char**)
    {
    
        auto f = std::find_if(
            boost::make_counting_iterator<int>(0),
            boost::make_counting_iterator<int>(20),
            [](int i){return i * i == 16;});
        cout << std::distance(
            boost::make_counting_iterator<int>(0),
            f) << endl;
    
        return 0;
    }
    

    I think that this approach is problematic in many ways. In the above, in particular, note that it searches for such numbers up to 20.