首页 > 解决方案 > 如何使用 Range-v3 模拟 boost::algorithm::find_if_backward?

问题描述

我一直在广泛使用boost::algorithm::find_if_backward前向迭代器来获取满足谓词的范围内的最后一个元素。

如何使用 Range-v3 完成相同的任务?

这是我的尝试,看起来有点笨拙;而且我什至不确定是否足够强大。实际上,正如评论中所建议的那样,代码不够健壮,因为当没有找到任何元素时,range_it_to_last_2最终会变成std::next(v.begin(), -1),这是未定义的行为,我相信。

#include <algorithm>
#include <boost/algorithm/find_backward.hpp>
#include <boost/hana/functional/partial.hpp>
#include <iostream>
#include <range/v3/algorithm/find_if.hpp>
#include <range/v3/view/reverse.hpp>

using boost::algorithm::find_if_backward;
using ranges::find_if;
using ranges::views::reverse;

auto constexpr is_2 = boost::hana::partial(std::equal_to<>{}, 2);

int main() {
    std::vector<int> v{0,1,2,2,2,3};

    // What I have been doing so far:
    auto boost_it_to_last_2 = find_if_backward(v, is_2);

    // The Range-v3 analogous I could come up with, but it's ugly:
    auto range_it_to_last_2 = std::next(find_if(v | reverse, is_2).base(), -1);

    for (auto it = v.begin(); it <= boost_it_to_last_2; ++it) {
        std::cout << *it << ' ';
    } // prints 0 1 2 2 2
    std::cout << std::endl;
    for (auto it = v.begin(); it <= range_it_to_last_2; ++it) {
        std::cout << *it << ' ';
    } // prints 0 1 2 2 2
    std::cout << std::endl;
}

标签: c++algorithmboostfindrange-v3

解决方案


假设您总是知道找到了匹配项,为什么不简化为以下内容,得到相同的输出:

住在神螺栓上

#include <algorithm>
#include <boost/algorithm/find_backward.hpp>
#include <boost/hana/functional/partial.hpp>
#include <fmt/ranges.h>
#include <range/v3/algorithm/find_if.hpp>
#include <range/v3/view/subrange.hpp>
#include <range/v3/view/reverse.hpp>

using boost::algorithm::find_if_backward;
using ranges::find_if;
using ranges::views::reverse;
using ranges::subrange;

auto constexpr pred = boost::hana::partial(std::equal_to<>{}, 2);

int main() {
    std::vector<int> v {0,1,2,2,2,3};
    auto boost_match = find_if_backward(v, pred);
    auto range_match = find_if(v | reverse, pred).base();

    static_assert(std::is_same_v<decltype(boost_match), decltype(range_match)>);

    fmt::print("boost: {}\nrange: {}\n",
            subrange(v.begin(), boost_match+1),
            subrange(v.begin(), range_match));
}

印刷

boost: {0, 1, 2, 2, 2}
range: {0, 1, 2, 2, 2}

(一些有趣的玩具拼写: https ://godbolt.org/z/ccPKeo )


推荐阅读