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

时间:2016-02-17 12:17:55

标签: c++ stl-algorithm

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

例如,请考虑以下函数

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

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

1 个答案:

答案 0 :(得分:5)

假设您可以使用类似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个这样的数字。