C++ 将标准库算法应用于函数

C++ apply standard library algorithms to functions

有没有办法将非修改标准库算法应用于离散函数而不是容器?

例如,考虑以下函数

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

如何使用 std::findstd::lower_bound 来搜索值 49,即算法应该 return 7?最简单的方法是将 return 放入向量中并将算法应用于向量——但这显然效率低下。

假设您可以使用 boost::iterator::counting_iterator 之类的东西。例如,下面发现 4 是平方为 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;
}

我认为这种方法在很多方面都有问题。在上面,特别注意,它搜索最多 20 个这样的数字。