zip_iterator and lower_bound

zip_iterator and lower_bound

本文关键字:bound lower iterator zip and      更新时间:2023-10-16

我不知道如何用zip_iterator来称呼lower_bound

这不会编译:

#include <boost/iterator/zip_iterator.hpp>
#include <vector>
#include <algorithm>
void main()
{
    typedef int Key;
    typedef double Value;
    typedef boost::tuple<typename std::vector<Key>::iterator,
                         typename std::vector<Value>::iterator> the_iterator_tuple;
    typedef boost::zip_iterator<the_iterator_tuple> the_zip_iterator;
    std::vector<Key>   keys_;
    std::vector<Value> values_;
    // Add values to keys_ and values_...
    auto it = std::lower_bound(
        the_zip_iterator(the_iterator_tuple(keys_.begin(), values_.begin())),
        the_zip_iterator(the_iterator_tuple(keys_.end(), values_.end())),
        123,
        [](const the_iterator_tuple & it, const int v) -> bool { return *boost::get<0>(it) < v; }
    );
    // Use "it"...
}

VS2010 说它"无法将参数 1 从'int'转换为'const std::_Vector_iterator<_Myvec> &'"(加上同一错误的其他几十件事),但它与一个晦涩的 boost::tuple 构造函数有关,而不是与给定的 lambda 有关。

我做错了什么?

这看起来像VS2010中的"概念检查"错误。

25.4.3.1 [下限]/p1:

要求:: [first,last)的元素e应划分为 尊重表达e < valuecomp(e, value)

即只需要*it < v

upper_bound算法有相反的要求:v < *itequal_range需要两种表达式才能工作。

std::lower_bound(it, end, v)需要能够同时执行*it < vv < *it。函数对象仅支持其中之一。

既然对此有评论,就留下上面的声明:事实并非如此。正如霍华德所指出的,比较是使用comp(*it, v)所必需的,也就是说,这个操作不需要对称。

但是,查看boost::zip_iterator<It0, It1>的文档似乎*it产生了boost::tuple<typename It0::reference, typename It1::reference>。因此,添加typedef

typedef boost::tuple<typename std::vector<Key>::reference,
                     typename std::vector<Value>::reference> the_reference_tuple;

。并将 lambda 更改为

[](the_reference_tuple const& it, int v) { return it.get<0>() < v; }

解决了使用 GCC 和 CLANG 的编译问题。