C++的哨兵while循环
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2176711/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Sentinel while loop for C++
提问by yihangho
Can anyone tell me what is sentinel while loop in C++? Please give me an example using sentinel while loop.
谁能告诉我什么是 C++ 中的 while 循环哨兵?请给我一个使用哨兵 while 循环的例子。
回答by MSalters
A "sentinel" in this context is a special value used to indicate the end of a sequence. The most common sentinel is \0 at the end of strings. A "sentinel while loop" would typically have the form:
在此上下文中的“哨兵”是用于指示序列结束的特殊值。最常见的标记是字符串末尾的 \0。“哨兵 while 循环”通常具有以下形式:
while (Get(input) != Sentinel) {
Process(input);
}
回答by Yin Zhu
A sentinel is a special value, e.g. boolean value, extremely big or small. It is used to determine when to stop the loop.
哨兵是一个特殊的值,例如布尔值,非常大或非常小。它用于确定何时停止循环。
A good example is in the implementation of merge sort, e.g. read page 4 of http://www.cs.princeton.edu/courses/archive/spr07/cos226/lectures/04MergeQuick.pdf.
一个很好的例子是合并排序的实现,例如阅读http://www.cs.princeton.edu/courses/archive/spr07/cos226/lectures/04MergeQuick.pdf 的第 4 页。
回答by San Jacinto
As an addendum to JRL's answer..
作为JRL答案的附录..
Please note that there was nothing wrong with asking this question, but in the future you may find more immediate help by going to dictionary.com and looking up words you don't know.
请注意,提出这个问题并没有错,但将来您可能会通过访问 dictionary.com 并查找您不认识的单词来获得更直接的帮助。
edit: in this case, the dictionary leaves nothing for you to think on. Here is definition 3 :)
编辑:在这种情况下,字典没有让你思考。这是定义 3 :)
3 Also called tag. Computers. a symbol, mark, or other labeling device indicating the beginning or end of a unit of information.
回答by Will
A sentinal is a special value in a list of items that will always cause the iterator to stop.
sentinal 是项目列表中的一个特殊值,它总是会导致迭代器停止。
For example, the zero terminator in an ASCIIZ string acts as a sentinal.
例如,ASCIIZ 字符串中的零终止符充当一个标记。
Linked lists often have NULL pointers and so.
链表通常有 NULL 指针等等。
回答by JRL
It's usually a boolean (true or false) variable that is set to false when a condition is not satisfied and set to true when it is. Then we can loop so long as the sentinel is false.
它通常是一个布尔值(真或假)变量,当条件不满足时设置为假,条件满足时设置为真。然后我们可以循环,只要哨兵是假的。
Example:
例子:
bool acceptedAnswer = false;
while (acceptedAnswer == false)
{
refreshPage();
if (hasBeenAccepted())
{
acceptedAnswer = true;
}
}