【发布时间】:2023-03-22 13:32:02
【问题描述】:
根据Wikipedia,
在计算机编程中,哨兵值(也称为标志值、跳闸值、流氓值、信号值或虚拟数据)是算法上下文中的特殊值,使用它的存在作为终止条件,通常在循环或递归算法中。
一个常见的例子是当数组大于填充它的数据时,在正整数数组的末尾使用-1 来表示数据的结尾。
但是,当我们使用-1 不是为了确保终止,而只是作为一个不可能的值时呢?例如:
# `a` is an array with the numbers from 0 to 4, in random order.
# We will use `b` to track where in `a` each number is. The position in `b`
# denotes the number, and the value denotes the index in `a`.
# `calculate_indices()` is a function that does this.
a = [3, 4, 1, 0, 2]
b = [-1, -1, -1, -1, -1]
calculate_indices(a, b)
print(b) => [3, 2, 4, 0, 1]
如果我们将b 初始化为[0, 0, 0, 0, 0],这是行不通的,因为0 在这里有真正的含义——即a 中的第0 个位置。因此我们使用一个不可能的值,-1。
这种用法有名称吗?
【问题讨论】:
-
维基百科的定义似乎相当严格。我之前听说过
find函数返回的 -1 被称为标记值。 -
@Carcigenicate 在more research 之后,看来你是对的。如果您想添加答案,我会接受它
-
我很欣赏这个手势,但我不喜欢在这样的车里写强制答案,因为这只是一种预感。这当然是适合自我回答的时候。
标签: computer-science terminology