【问题标题】:Is one-line initialization of a <set> possible with C++20 <ranges>?是否可以使用 C++20 <ranges> 对 <set> 进行单行初始化?
【发布时间】:2021-03-21 11:24:43
【问题描述】:

我想知道在 C++20 中使用 &lt;ranges&gt; 是否最终可以从序列中选择并在一行中初始化 set,就像在 C# 中使用 IEnumerable 一样。这可能需要将&lt;ranges&gt; 对象转换为std::initializer_list

C#:

int[] sequence = new int[] { 0,1,2,3,4 };
HashSet<int> set = new HashSet<int>(sequence.Where((int i) => i % 2 == 0));

C++:

std::vector<int> sequence { 0,1,2,3,4 };
auto matcher = sequence | std::ranges::views::filter([](int i) { return !(i % 2); });
std::set<int> myset(matcher.begin(), matcher.end());

我想做这样的事情:

std::vector<int> sequence { 0,1,2,3,4 };
std::set<int> myset { sequence | std::ranges::views::filter([](int i) { return !(i % 2); }) };

【问题讨论】:

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


【解决方案1】:

其实目前是不可能的,但是在不久的将来,我们可以得到ranges::to,它会有这样的功能。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-03-16
    • 2013-01-19
    • 2021-12-03
    • 1970-01-01
    • 2020-07-18
    • 2022-01-21
    • 1970-01-01
    相关资源
    最近更新 更多