c++ - 如何使用 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;
}
解决方案
假设您总是知道找到了匹配项,为什么不简化为以下内容,得到相同的输出:
#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 )
推荐阅读
- php - AWS PHP SDK:存储桶加密不起作用
- android - 带有深层链接的 Android 导航组件:onNewIntent 被多次调用
- java - 如何使用健康指标?
- elixir - Elixir 地图返回 nil
- java - Android 在屏幕上录制音频
- visual-studio-2019 - Sonarlint 未突出显示 Visual Studio Enterprise 2019 中的问题
- javascript - 多个 WebBrowser 控件 WPF 中的集线器连接失败
- oracle - DBMS_PARALLEL_EXECUTE 和间接授予对过程的授权
- python - 如何使用 Python unittest 在另一个方法中模拟一个方法?
- python - Tweepy 地理搜索不断返回超出范围的推文