C++ C++;:如何使用boost::range查找max_元素?
我试图将迭代器返回到筛选范围内的最大元素。以下是我到目前为止的情况:C++ C++;:如何使用boost::range查找max_元素?,c++,boost,boost-lambda,boost-range,C++,Boost,Boost Lambda,Boost Range,我试图将迭代器返回到筛选范围内的最大元素。以下是我到目前为止的情况: #include <boost/lambda/lambda.hpp> #include <boost/range/adaptors.hpp> #include <boost/range/algorithm.hpp> #include <vector> #include <iostream> using namespace boost::adaptors; using
#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;
}
#包括
#包括
#包括
#包括
#包括
使用名称空间boost::适配器;
使用名称空间boost::lambda;
使用名称空间std;
int main()
{
向量x={100150200110};
auto it=boost::max|u元素(x |索引(0)|过滤(_1>100));/*这里的问题*/
cout(100));
并检查boost::empty(另一个\u范围)是否为空。这是唯一的选项吗?谢谢。出现您遇到的特定错误,因为boost lambda不可复制分配。以下是实现相同消息的简单方法:
auto f1 = _1 > 100;
auto f2 = f1;
f2 = f1; // same error
如果您向过滤的boost.phoenix(无论如何,您都应该使用它,boost.lambda正在走向有利于phoenix的弃用)、手工编写的结构或旧的忠实的std::bind2nd(std::greater(),100)
提供一个可复制分配的函子,那么这一行将使用clang++编译:
第二次演示:
凤凰城演示:
由于一些boost.concept检查,它在gcc中失败,这可能是一个错误,但这是一个没有意义的问题,因为filtered
的结果是boost::filtered_range
,其迭代器没有.index()
成员函数
根据评论进行编辑:
将迭代器与原向量中的迭代器进行比较是不可行的。但是,由于您使用了向量,而且它仍然可以访问,所以您可以比较地址,因为索引的和过滤的都不复制
#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';
}
#包括
#包括
#包括
#包括
#包括
#包括
使用名称空间boost::适配器;
使用名称空间boost::phoenix::占位符;
int main()
{
向量x={100150200110};
auto it=boost::max|u元素(x |索引(0)|过滤(arg1<110));
断言(&x[0]小心使用指令:名称空间std
和名称空间boost::lambda
都有类似\u 1
@TemplateRex的占位符STL占位符在名称空间std::占位符
中,因此在这种情况下没有冲突。我明白了,谢谢。我编辑了原始帖子以反映我使用boost::function进行的更改。如果我将迭代器返回到最大的元素,是否有方法检查此迭代器是否在范围内?将其与boost::end(x)进行比较会给出另一个错误。
auto f1 = _1 > 100;
auto f2 = f1;
f2 = f1; // same error
#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';
}