为什么是标准迭代器范围[begin,end)而不是[begin,end]? [英] Why are Standard iterator ranges [begin, end) instead of [begin, end]?
问题描述
为什么标准将 end()
定义为一个结束而不是实际结束?
Why does the Standard define end()
as one past the end, instead of at the actual end?
推荐答案
最好的参数很容易就是 Dijkstra自己:
The best argument easily is the one made by Dijkstra himself:
-
您希望范围的大小是一个简单的区别<
You want the size of the range to be a simple difference end − begin;
包括当序列退化为空时下界更加自然 ,并且因为替换(排除下限)将需要存在开头之前的哨兵值。
including the lower bound is more "natural" when sequences degenerate to empty ones, and also because the alternative (excluding the lower bound) would require the existence of a "one-before-the-beginning" sentinel value.
你仍然需要证明为什么你开始计数为零而不是一个,但这不是你的问题的一部分。
You still need to justify why you start counting at zero rather than one, but that wasn't part of your question.
[begin,end]约定背后的智慧会在你有任何类型的算法处理多个嵌套或迭代的调用到基于范围的构造时自动返回。相比之下,使用双闭合范围将导致一个一个,非常令人不快和噪声的代码。例如,考虑分区[ n 0 , n 1 1 , n 2 )[ n em> 3 )。另一个例子是标准迭代循环 for(it = begin; it!= end; ++ it)
,它运行 end- begin
次。如果两端都包含–相应的代码将不太可读;并设想如何处理空白区域。
The wisdom behind the [begin, end) convention pays off time and again when you have any sort of algorithm that deals with multiple nested or iterated calles to range-based constructions, which chain naturally. By contrast, using a doubly-closed range would incur off-by-ones and extremely unpleasant and noisy code. For example, consider a partition [n0, n1)[n1, n2)[n2,n3). Another example is the standard iteration loop for (it = begin; it != end; ++it)
, which runs end - begin
times. The corresponding code would be much less readable if both ends were inclusive – and imagine how you'd handle empty ranges.
最后,我们还可以做一个好的参数,为什么计数应该从零开始:对于范围的半开公约我们刚刚建立,如果你给一个范围的 N 元素(比如枚举数组的成员),那么0是自然的开始,所以你可以写范围为[0,
Finally, we can also make a nice argument why counting should start at zero: With the half-open convention for ranges that we just established, if you are given a range of N elements (say to enumerate the members of an array), then 0 is the natural "beginning" so that you can write the range as [0, N), without any awkward offsets or corrections.
简而言之:我们没有看到号码<$ c $ c> 1 在基于范围的算法中的任何地方都是[begin,end)约定的直接结果和动机。
In a nutshell: the fact that we don't see the number 1
everywhere in range-based algorithms is a direct consequence of, and motivation for, the [begin, end) convention.
这篇关于为什么是标准迭代器范围[begin,end)而不是[begin,end]?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!