C++ Iterator dereference and prefix increment/decrement style? Is *--Iter ok style wise?

后端 未结 4 1607
[愿得一人]
[愿得一人] 2021-01-22 22:56

In coding with C++ iterators if you wanted to get the previous value to what an iterator points to would you write:

*--Iter

or would you think

相关标签:
4条回答
  • 2021-01-22 23:22

    Even if you get one of these to work as you expect, they're both hard to read. Does this have to be done in a single statement?

    0 讨论(0)
  • 2021-01-22 23:33

    It doesn't matter as far as program correctness is concerned. But I always express this as *(--Iter) because this is more self-documenting and easier to understand to human beings than *--Iter.

    0 讨论(0)
  • 2021-01-22 23:34

    I would use the latter for clarity, but both are completely valid and equivalent.

    Note: In case there's any confusion, that syntax doesn't just get the value of the predecessor iterator, it moves the iterator itself backwards. If you want to get the value of the predecessor iterator without modifying the one you have then you need a temporary.

    0 讨论(0)
  • 2021-01-22 23:42

    Either is fine. Use the one preferred by any coding standard you need to obey, or the one you prefer personally.

    0 讨论(0)
提交回复
热议问题