首页 > 解决方案 > Ranges-v3 组合在使用 range::views::counted(1) 时产生错误

问题描述

我正在使用范围库(eric niebler 范围)并且我正在尝试编写范围组合,但我使用的范围::views::counted(1) 选项不起作用。

我试图从右边忽略目标时间再减去 1 个周期(5 分钟)。然后,提取下一个 1x 值。

这是我想要实现的视觉示例(与下面的代码无关)。

time
1:00 1:01 1:02 1:03 1:04 1:05 1:06 1:07 1:08 1:09 1:10 1:11 1:12 1:13 1:14 1:15 1:16
                                                                                ^start_reading
                                                                      ^target_time
                         ^target_time minus 1x5mins periods, 
                          start extraction here 
                    ^extract the value associated with this time

到目前为止我开发的代码如下:

#include <fmt/format.h>
#include <range/v3/all.hpp>
#include <chrono>
#include <vector>
#include <iostream>

struct th {
    std::chrono::system_clock::time_point timestamp;
    double h;
};

constexpr auto period_start(const std::chrono::system_clock::time_point timestamp,
                            const std::chrono::minutes timeframe)
    -> std::chrono::system_clock::time_point
{
    using namespace std::chrono;

    const auto time = hh_mm_ss{floor<minutes>(timestamp - floor<days>(timestamp))};
    return timestamp - (time.minutes() % timeframe);
}

auto main() -> int
{
    using namespace std::chrono_literals;
    namespace views = ranges::views;

    const auto timeframe = 5min;

    { 
        const auto tp = std::chrono::system_clock::from_time_t(0); // just used for populating the example vector
        const auto timestamped_h = std::vector<th>{
            {tp + 0min , 1.0}, {tp + 1min , 1.1}, {tp + 3min , 1.2}, {tp + 4min , 1.2},
            {tp + 5min , 0.8}, {tp + 6min , 0.9}, {tp + 7min , 1.0},
            {tp + 10min, 1.1}, {tp + 11min, 1.3}, {tp + 12min, 1.2}, {tp + 13min, 1.1}, {tp + 14min, 0.9},
            {tp + 15min, 0.8}, {tp + 16min, 1.4}, {tp + 17min, 1.3}, {tp + 18min, 1.6}, {tp + 19min, 1.5}
        };

        const auto target_tp = tp + 17min;
        const auto remove_candle = [target_tp,timeframe](const auto& lhs) { 
            return lhs.timestamp >= period_start(target_tp - 1* timeframe,timeframe); 
        };

        auto pivots = timestamped_h 
            | views::reverse
            | views::remove_if(remove_candle)
            //| views::filter(remove_candle)
            | ranges::views::counted(1);

        for(auto p : pivots)
            std::cout << p.h << std::endl;
    }
}

但是 range::views::counted(1) 选项会产生以下错误: error: no match for call to '(const ranges::views::counted_fn) (int)'

这里提供了一个小径区域

请问我做错了什么?

标签: c++c++20std-ranges

解决方案


我需要的是::counted,它是::take。最后结果:

        auto pivots = timestamped_h 
            | views::reverse
            | views::remove_if(remove_candle)
            | ranges::views::take(1);

推荐阅读