gpt4 book ai didi

C++:如何使用 boost::range 查找 max_element?

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:55:03 26 4
gpt4 key购买 nike

我正在尝试将迭代器返回到过滤范围内的最大元素。这是我目前所拥有的:

#include <boost/lambda/lambda.hpp>
#include <boost/range/adaptors.hpp>
#include <boost/range/algorithm.hpp>
#include <vector>
#include <iostream>

using namespace boost::adaptors;
using namespace boost::lambda;
using namespace std;

int main ()
{
vector<double> x = {100, 150, 200, 110};
auto it = boost::max_element(x | indexed(0) | filtered(_1>100)); /* problem here */
cout << it.index() << endl;

return 0;
}

我希望代码打印出 vector x 中具有最大元素(即 2)的索引,但不幸的是它无法编译(Linux 64 位,GCC 4.7.2),问题出在上面指出的行中.我从编译器(除其他外)得到的第一个编译错误如下:

/boost/tuple/detail/tuple_basic.hpp:396:36: 错误:分配只读成员‘boost::tuples::cons::head’

知道我做错了什么吗?或者我还能如何实现我想要做的事情?提前致谢!

编辑:

将有问题的行更改为:

auto it = boost::max_element<boost::return_found>(x | sliced(1,4) |   filtered(boost::function<bool(double)>(_1>100)));

似乎返回了最大元素的迭代器。但是,有没有办法检查迭代器是否在范围内?将它与 boost::end(x) 进行比较会给我一个错误。唯一能想到的就是返回

auto another_range = boost::max_element<boost::return_found_end>(x | sliced(1,4) |   filtered(boost::function<bool(double)>(_1>100)));

并检查是否 boost::empty(another_range)。这是唯一的选择吗?谢谢。

最佳答案

出现您遇到的特定错误是因为 boost lambda 不是 CopyAssignable。这是实现相同消息的更简单方法:

auto f1 = _1 > 100;
auto f2 = f1;
f2 = f1; // same error

如果您向 filtered 提供 CopyAssignable 仿函数,boost.phoenix(无论如何你都应该使用它,boost.lambda 正在走向弃用以支持 phoenix),一个手写的结构,或者老忠实的std::bind2nd(std::greater<double>(), 100) ,这一行用 clang++ 编译:

bind2nd 演示:http://liveworkspace.org/code/2xKZIf

凤凰演示:http://liveworkspace.org/code/18425g

由于某些 boost.concept 检查,gcc 失败,这可能是一个错误,但它是一个有争议的问题,因为 filtered 的结果是boost::filtered_range ,其迭代器没有 .index()成员函数。

编辑回应评论:比较 filtered_range 中的迭代器和原始 vector 中的迭代器是行不通的。但是,由于您使用了 vector ,并且它仍然可以访问,因此您可以比较地址,因为 indexed 都不是也不filtered复制

#include <vector>
#include <iostream>
#include <cassert>
#include <boost/range/adaptors.hpp>
#include <boost/range/algorithm.hpp>
#include <boost/phoenix.hpp>

using namespace boost::adaptors;
using namespace boost::phoenix::placeholders;

int main ()
{
std::vector<double> x = {100, 150, 200, 110};
auto it = boost::max_element( x | indexed(0) | filtered(arg1 < 110) );
assert(&x[0] <= &*it && &*it < &x[0] + x.size());
std::cout << "Element " << *it << " is at index " << &*it - &x[0] << '\n';
}

演示 http://liveworkspace.org/code/1zBIJ9

或者,对于更通用的解决方案,您可以将 vector 转换成对 vector (当 boost 获得 zip 适配器时,它可以用 counting_range 整齐地压缩),并携带原始序列索引以及所有转换。

关于C++:如何使用 boost::range 查找 max_element?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15723885/

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