代表间隔或范围? [英] Representing intervals or ranges?
问题描述
通常,无论何时表示任何类型的范围,都可以选择几种类型的值作为范围的开始和结束。例如,如果要包含整数1、2、3、4、5的范围,则可以选择以下可能的值:
In general, whenever you're representing a range of any kind, you have several choices for what kinds of values to choose for the beginning and ending of your range. For example, if you want to have a range containing the integers 1, 2, 3, 4, 5 you could choose these possible values:
- 开始= 0,结束= 5(又名开始< x< =结束)
- 开始= 1,结束= 5(又名开始< = x< =结束)
- 开始= 0,结束= 6(又名开始< x< end)
- 开始= 1,结束= 6(又名开始< = x< end(C ++ STL和许多其他库似乎选择了此)。
- begin = 0, end = 5 (aka begin < x <= end)
- begin = 1, end = 5 (aka begin <= x <= end)
- begin = 0, end = 6 (aka begin < x < end)
- begin = 1, end = 6 (aka begin <= x < end (the C++ STL and many other libraries seem to choose this)).
我不确定采取什么措施我应该使用这些选项之一。
I'm not sure what measures I should use to choose one of these options.
推荐答案
我希望有人能给我一个指向电子战Dijkstra 写了关于这个话题的文章。我设法将正确的搜索字词插入Google,并找到了我要找的链接。该文件为为什么编号应从0开始,还介绍了为什么范围应以半开间隔[begin,end)表示。
I was hoping someone would give me a link to a nice paper that E.W. Dijkstra wrote on the topic. I managed to plug just the right search terms into Google, and found the link I was looking for. The paper is "Why numbering should start at 0" and also covers why ranges should be represented with a half open interval [begin, end).
基本参数有几段:
- 对编程环境(Xerox PARC的Mesa编程语言)有直接的经验,该环境支持所有4种不同的选择,导致人们经常在[开始,结束]上进行标准化操作,
- 如果您的间隔从0开始,则开始为-1或类似的东西就很尴尬和残缺。这充分说明了从
开始
开始的间隔(即所有开始< = x选择)。 - 用于确定间隔大小,用于计算下一个相邻间隔的开始,并且如果end是一个过去的开始,那么一大堆其他类似的东西也可以很好地解决。例如,大小为
结束-开始
。end
是下一个相邻间隔的开始
。在您的计算中出现一次错误的机会就更少了。
- 在相关说明中,空白范围是
[开始,开始)
,非常明显。如果两端都关闭,它必须是相当笨拙的[开始,开始-1]
。这个范围从0开始特别尴尬。
- 在相关说明中,空白范围是
- Direct experience with a programming environment (the programming language Mesa at Xerox PARC) that had support for all 4 different choices resulted in people standardizing on [start, end) because of frequent errors made with all the other choices.
- If you have an interval that starts at 0, having the start be -1 or something similar is just awkward and broken. This argues strongly for the interval starting at
begin
(i.e. all the begin <= x choices). - The math for determining the interval size, for computing the start of the next adjacent interval, and a whole bunch of other similar things just works out nicely if end is one past start. For example, the size is
end - begin
. Andend
is thebegin
of the next adjacent interval. There are fewer chances for off-by-one errors in your calculations.- On a related note, the empty range is
[begin, begin)
, and very obvious. It would have to be the rather awkward[begin, begin - 1]
if it were closed on both sides. This is especially awkward of your range begins at 0.
- On a related note, the empty range is
这篇关于代表间隔或范围?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!