1

我正在练习vectors并且ranges陷入c++ 20以下状态。

#include <iostream>
#include <vector>
#include <random>
#include <ranges>
#include <algorithm>

namespace ranges = std::ranges;

struct Model
{
    double next_event_time;
};

std::vector<Model> generate_examples(int number)
{
    // A uniform random number generator object
    // Used as the source of randomness
    std::default_random_engine generator;

    // Calls () operator on generator to get uniformly-distributed integers
    // then transforms the obtained values to output the disired distribution

    // Will uniformly generate values between 0 ~ 1
    std::uniform_real_distribution<double> distribution(0.0, 1.0);

    std::vector<Model> models;

    for (auto i = 0; i < number; i++)
    {
        models.push_back(Model{.next_event_time = distribution(generator)});
    }

    return models;
}

Model get_next_model(const std::vector<Model> &models)
{
    ranges::sort(models | std::views::transform([](const Model &x) { return x.next_event_time; }));

    return models[0];
}

int main()
{
    std::vector<Model> models = generate_examples(10);

    for (const auto &model : models)
        std::cout << model.next_event_time << std::endl;
}

我编译了代码g++ 10.2并得到了错误

 error: no match for call to '(const std::ranges::__sort_fn) ~~~
ranges::sort(models | std::views::transform([](const Model &x) { return x.next_event_time; }));

而不是std::views::transform,我也试过

  1. 拉姆达表达式
  2. ranges::sort(models, {}, &Model::next_event_time)

但他们都产生了类似no match for call to的错误。为什么会这样?

4

1 回答 1

2

你的功能应该是这样的:

Model get_next_model( std::vector<Model> models)
{

    ranges::sort(models, ranges::less{}, [](const Model &x) { return x.next_event_time; });

    return models[0];
}

有两个问题:

  1. 你不能对 const 对象进行排序(所以 remove const&
  2. sort的签名ranges::less需要在投影之前进行排序( )。而变换在这里没有意义
于 2021-02-28T00:39:26.910 回答