Why can't a range be sorted in range-v3?

筅森魡賤 提交于 2021-01-27 21:00:53

问题


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

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.

Why is there no view::sort ? It would fit nicely in the above composition of ranges.


回答1:


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.



来源:https://stackoverflow.com/questions/60338142/why-cant-a-range-be-sorted-in-range-v3

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!