简体   繁体   English

为什么 range::sort 返回一个迭代器?

[英]Why does ranges::sort return an iterator?

I can see that std::sort returns void .我可以看到std::sort返回void But now that ranges have been added to the C++20 Standard, why does std::ranges::sort return an iterator ?但是现在ranges已经添加到 C++20 标准中,为什么std::ranges::sort返回一个iterator cppreference specifies: cppreference指定:

Return value返回值

An iterator equal to last.等于 last 的迭代器。

  1. What's the rational behind that choice?这种选择背后的原因是什么?
  2. What's the use case advantage compared to void ?void相比,用例优势是什么?

You don't have to pass an end iterator to the algorithms in std::ranges .您不必将结束迭代器传递给std::ranges中的算法。 You can pass a sentinel instead, which is something comparable to an iterator, but it's not itself an iterator (it can't be dereferenced or incremented).您可以改为传递一个哨兵,它类似于迭代器,但它本身不是一个迭代器(它不能被取消引用或递增)。 Think of how this might be useful if you wanted to pass a null-terminated string to an algorithm.想一想如果您想将一个以 null 结尾的字符串传递给算法,这可能会有什么用处。

std::ranges::sort necessarily find the end of the sequence while doing it sorting. std::ranges::sort在进行排序时必须找到序列的结尾。 That's useful information, so it is returned.这是有用的信息,所以它被返回。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM