STL迭代器:前缀增量更快?

时间:2011-03-07 19:03:43

标签: c++ stl

  

可能重复:
  Preincrement faster than postincrement in C++ - true? If yes, why is it?
  Is there a performance difference between i++ and ++i in C++?

我被告知在使用STL及其迭代器时,我应该始终使用++iter而不是iter++

我引用:

  

因为它只能更快,从不慢

这是真的吗?

2 个答案:

答案 0 :(得分:11)

是。一般来说都是如此。后缀增量负担着保留和返回迭代器的值的任务。这需要时间和精力,这通常会使它变慢。

对于所有实现传统前/后语义的重载递增/递减运算符通常都是正确的。

这个话题被打败了。在这里搜索“prefix postfix”以获取大量更详细的解释。

答案 1 :(得分:7)

你可以在这个例子中看到创建了一个temp,在postfix中...这比前缀慢,其中没有创建高级对象

// Define prefix increment operator.
Point& Point::operator++()
{
   _x++;
   _y++;
   return *this;
}

// Define postfix increment operator.
Point Point::operator++(int)
{
   Point temp = *this;
   ++*this;
   return temp;
}

++它比iter ++更快,因为没有创建对象的副本