简体   繁体   English

输入迭代器 - Star和Postfix-Operator

[英]Input Iterator - Star and Postfix-Operator

Is it valid to do this on an input iterator *it++ ? 在输入迭代器*it++上执行此操作是否有效?

I understand the code as follow, that it dereference the iterator and gives me the value and then step one ahead. 我理解代码如下,它取消引用迭代器并给我值,然后提前一步。

In the c++ reference the * operator is lower than the postfix operator: http://en.cppreference.com/w/cpp/language/operator_precedence 在c ++引用中,*运算符低于后缀运算符: http//en.cppreference.com/w/cpp/language/operator_precedence

But I read this style is bad practice. 但我读到这种风格是不好的做法。 Why? 为什么?

Is it valid to do this on an input iterator *it++ ? 在输入迭代器*it++上执行此操作是否有效?

Yes, that is valid. 是的,这是有效的。 The iterator will be incremented, its previous value will be returned, and you will dereference that returned iterator. 迭代器将递增,将返回其先前的值,并且您将取消引用返回的迭代器。

But I read this style is bad practice. 但我读到这种风格是不好的做法。 Why? 为什么?

Consider these two implementations I've just pulled out of some graph code I wrote a while back: 考虑一下我刚刚从我写的一些图形代码中提取的这两个实现:

// Pre-increment
BidirectionalIterator& operator++()
{
    edge = (edge->*elem).next;
    return *this;
}

// Post-increment
BidirectionalIterator operator++(int)
{
    TargetIterator oldval(list, edge);
    edge = (edge->*elem).next;
    return oldval;
}

Notice that for post-increment, I need to first construct a new iterator to store the previous value which will be returned. 请注意,对于后增量,我需要首先构造一个新的迭代器来存储将返回的先前值。

If it's simple and clear to write your program to make use of pre-increment, there may be better performance, less work for the compiler to do, or both. 如果编写程序以使用预增量是简单明了的,那么可能会有更好的性能,编译器的工作量更少,或者两者兼而有之。

Just don't go crazy on this (for example, rewriting all your loops)! 只是不要为此疯狂(例如,重写所有循环)! That would likely be micro-optimization. 这可能是微观优化。 However, the reason people say it's good practice is that if you get into a habit of using pre-increment as default then you get (potentially) better performance by default. 然而,人们说这是一个好习惯的原因是,如果你养成了使用预增量作为默认值的习惯,那么默认情况下你会获得(可能)更好的性能。

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

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