QnA*_*QnA 5 c++ c++20 std-ranges
为标题道歉,如果我知道如何更好地表达它,那么谷歌可能已经帮助了我......
我想要一个对象 Y,它代表容器 X 的视图,这样当我迭代 Y 时,它是 X 的向前或向后迭代。我想在不复制数据的情况下进行,因此新ranges库出现记在心里。
std::vector x{};
auto z = some_condition ? x : (x | std::views::reverse);
Run Code Online (Sandbox Code Playgroud)
显然,x和的类型(x|...)是不同的。我怎样才能使它们一致?
编辑:刚刚发现10 年前提出的以下问题,我想我想知道的是,ranges现在让事情变得更容易了吗?由于该解决方案仍然需要将 for 循环逻辑放入单独的函数或 lambda 中。
Apparently the types of x and (x|...) are different. How can I make them consistent?
You could make them consistent by using a type-erasing view for the ranges.
However, you must decide whether the potential runtime cost of such view is worth the goal that you're trying to achieve.
does ranges make things easier now?
It doesn't have an effect on this as far as I can tell. The same issue exists with iterators as well as ranges. Both can be worked around using type-erasure at the cost of potential runtime overhead.
Standard library doesn't provide an implementation of such type erasing range, nor a type-erasing iterator so you'll have to write your own (or as nearly always, use one written by someone else).
You can alternatively solve the problem with ranges the analogous way as in the linked iterator question, by avoiding their use in a single expression:
if (some_condition) {
auto z = x | std::views::all;
} else {
auto z = x | std::views::reverse;
}
Run Code Online (Sandbox Code Playgroud)