简体   繁体   English

这段C ++代码在做什么?

[英]What is this piece of c++ code doing?

I don't know how and why this piece of code works: 我不知道这段代码如何以及为什么起作用:

// postorder dfs
Iterator< Index<String<char> >, TopDown<ParentLink<Postorder> > >::Type
     myIterator(myIndex);
while (goDown(myIterator));
for (; !atEnd(myIterator); goNext(myIterator)) 
// do something with myIterator ( Traverse Through (Suffix)-tree )

It's an example from seqan and the interface is described here: API 这是来自seqan的示例,接口在此处描述: API

  1. How can the while affect the for-loop? while如何影响for循环?
  2. Why isn't the for loop initialized? 为什么不初始化for循环?

You've run into the fun parts of C++ - using language constructs in syntactically valid but difficult-for-human-parsing techniques. 您已经遇到了C ++的有趣部分-在语法上有效但人为难以解析的技术中使用语言构造。

while (goDown(myIterator));

This will "goDown(myIterator)" until it returns false. 这将是“ goDown(myIterator)”,直到返回false。 Then it will continue onto the for loop. 然后它将继续进入for循环。 It's looping over nothing - but that's okay, because the function goDown is doing work. 它什么也没有循环-没关系,因为功能goDown正在起作用。

for (; !atEnd(myIterator); goNext(myIterator)) 

This doesn't initialize anything, but tests that it's not atEnd(myIterator) - while it's not, it will goNext(myIterator). 这不会初始化任何内容,但会测试它是否不是atEnd(myIterator)-否则,它将进行goNext(myIterator)。 It could also be written as a while loop to make it slghtly easier to understand: 也可以将其编写为while循环,以使其更容易理解:

while(!atEnd(myIterator)) 
{
    goNext(myIterator));
}

So the code will: 因此,代码将:

  1. Go down until goDown() returns false - this means goDown is modifying myIterator each time 一直下去,直到goDown()返回false-这意味着goDown每次都在修改myIterator
  2. goNext() until it is atEnd() goNext()直到到达atEnd()

Clearly, goDown and goNext are taking their argument by reference and altering it. 显然, goDowngoNext通过引用接受其参数并对其进行更改。 So the answer to your two questions is, 1. the while calls goDown a number of times, altering myIterator as it goes, and this is the indirect influence you're talking about, since 2. the for starts with myIterator exactly as the while left it -- so of course it doesn't reassign it, that would undo all the while's work! 因此,您的两个问题的答案是:1. while多次调用goDown ,同时更改myIterator ,这是您正在谈论的间接影响,因为2. formyIterator完全相同, while离开它-因此当然不会重新分配它,这将撤消所有工作!

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

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