简体   繁体   中英

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 , ie 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.

Hypothetically, you could use something like boost::iterator::counting_iterator . Eg, 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM