gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 20:37:15 25 4
gpt4 key购买 nike

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

例如,考虑下面的函数

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

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

最佳答案

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

关于C++ 将标准库算法应用于函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35456514/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com