开发者

What STL container should i use to walk a tree?

I dont know whether bidirectional means i can write rbegin() or if i can decrease an iterator.

I have a tree that is forward only which isnt a problem. I'd like to walk it which is. What i am doing at the moment i开发者_如何学编程s every time i visit a branch i push current_iterator. Now the problem is i am iterating through a branch and called a function. The function needs to visit the previous nodes in the list.

So i wrote it=current_iterator and plan to write --it to rewind. As a quick test i wrote --o.begin()==o.end() to see if i can do this. I got a assert error.

I am using a deque. What container might i use that allows me to write = on an interator, go forward and backwards while in the middle of an iteration? It seems like i need to keep a copy of o as well so i could compare .begin() and .end(). What is the recommended container and technique?


Deque iterators are random-access. You can increment and decrement them.

The problem is probably that you tried to decrement the iterator returned by begin. Doing that is not guaranteed to give you the end of the list — deques aren't circular. (I think it's undefined behavior, so it could give you the end, but I doubt any implementations actually do it that way.)

In other words, your test of whether you can decrement iterators wasn't a valid test; the conclusion you drew from it that you can't decrement iterators isn't valid, either. You can decrement any valid deque iterator as long as the new location would also be valid.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜