The ranges TS已合并到C ++ 20中。我想知道用该提案实现类似Python的切片操作的最佳方法是什么?具体来说,假设a
是vector<int>
,如何实现:
a[:5]
(前5个元素)a[5:]
(从第5个元素到最后一个元素)a[2:4]
(第二和第三元素)a[2::-1]
(a [2],a [1],a [0])a[4:1:-2]
(a [4],a [2])答案 0 :(得分:3)
以下是我能够匹配您的示例的所有摘要,请以此为提示,以了解如何使用TS的current实现。
std::vector<int> elements{0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
// First five elements
std::vector<int> a = elements | ranges::view::take(5);
// From the 5-th elements to the end
std::vector<int> b = elements | ranges::view::drop(5);
// The 2nd and 3rd elements
std::vector<int> c = elements | ranges::view::slice(2, 4);
// The first 3 elements, in reverse
std::vector<int> d = elements | ranges::view::take(3) | ranges::view::reverse;
// Elements 2-4 inclusive, reversed, and then taking every 2nd element
std::vector<int> e = elements | ranges::view::slice(2, 5) | ranges::view::reverse | ranges::view::stride(2);