C++迭代器解引用和前缀递增/递减样式? *--Iter ok 风格明智吗?
在使用 C++ 迭代器进行编码时,如果您想获取迭代器指向的前一个值,您会写:
*--Iter
还是您认为最好添加括号,如下所示:
*(--Iter)
?
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 it better to add parentheses like so:
*(--Iter)
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
就程序的正确性而言,这并不重要。但我总是将其表达为
*(--Iter)
,因为这比*--Iter
更具有自我说明性,更容易被人类理解。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
.为了清楚起见,我会使用后者,但两者都是完全有效且等效的。
注意:为了防止出现任何混淆,该语法不仅获取前一个迭代器的值,还将迭代器本身向后移动。如果您想获取前驱迭代器的值而不修改已有的迭代器,那么您需要一个临时迭代器。
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.
即使您让其中之一按预期工作,它们都很难阅读。这必须在一个语句中完成吗?
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?
两者都可以。使用您需要遵守的任何编码标准首选的标准,或者您个人喜欢的标准。
Either is fine. Use the one preferred by any coding standard you need to obey, or the one you prefer personally.