自增表达式¶
迭代器自增¶
在迭代器的自增中,++iter和iter++虽然在功能上等价,但在效率上有所区别。
// Prefix form - ++it
// Increment `it` and returns a **reference** to same object
IteratorType& operator++();
//Postfix form - it++
// Increment `it` and returns a **copy** of the old value
IteratorType operator++(int);
简单来说,使用前者在进行自增操作后会直接返回迭代器的引用,而后者会返回自增前的值的拷贝。
Tip
迭代器是一个功能完备的对象,因此复制它通常比复制一个 int 更昂贵。
Bjarne’s Thoughts
++i is sometimes faster than, and is never slower than, i++. ... So if you’re writing i++ as a statement rather than as part of a larger expression, why not just write ++i instead? You never lose anything, and you sometimes gain something.