为什么不能在range-v3中对范围进行排序? [英] Why can't a range be sorted in range-v3?
问题描述
使用Range-v3(版本0.10.0)库,我试图从std :: vector构造一个范围,将其转换为另一个范围,最后对该范围进行排序.我期望排序步骤会产生另一个范围,以后可以使用.但是我能想到的最好的方法是:
Using the Range-v3 (release 0.10.0) library I was trying to construct a range from a std::vector, transform it into another range and finally sort that range. I expected the sort step to produce another range that I could consume later. But the best I could come up with was this:
std::vector<std::string> const input { "2", "3", "1" };
using namespace ranges;
std::vector<int> output = input
| views::transform([](std::string s) { return std::stoi(s); })
| to<std::vector>()
| actions::sort
请注意,在转换步骤之后和排序步骤之前,请使用 to< std :: vector>()
.当我只想对转换步骤产生的 range 进行排序时,这似乎分配了一个新的 std :: vector
.
Notice the use of to<std::vector>()
after the transform step and before the sort step. This seems to allocate a new std::vector
when all I wanted was to sort the range that the transform step had produced.
为什么没有 view :: sort
?它很适合以上范围的组成.
Why is there no view::sort
? It would fit nicely in the above composition of ranges.
推荐答案
转换后的范围只是一个视图,迭代视图时一次生成一个元素.无法排序,因为没有地方可以存储排序后的元素.假设的实现方式效率也很低,因为每次需要对排序进行比较时,都必须转换每个元素.
The transformed range is only a view, the elements are generated one at a time as the view is iterated. It can't be sorted as there is nowhere to store the sorted elements. A hypothetical implementation would also be inefficient as it would have to transform each element every time it needed to do a comparison for the sort.
您的解决方案将转换后的元素存储在向量中然后对其进行排序是正确的.
Your solution is correct to store the transformed elements in a vector then sort them.
这篇关于为什么不能在range-v3中对范围进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!