实际示例中何时使用后递减/递增与前递减/递增? [英] When is post-decrement/increment vs. pre-decrement/increment used in real-life examples?

查看:51
本文介绍了实际示例中何时使用后递减/递增与前递减/递增?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能的重复:
为什么在语句中其他任何地方都没有使用该值的情况下使用 ++i 而不是 i++ ?
在 C++ 中递增 - 何时使用 x++ 或 ++x?

i++ vs. ++i  

什么时候用在实际场景中?

When is this used in real scenarios?

推荐答案

很明显,当您想要返回旧值时,您可以使用后增量.

The obvious is when you want the old value returned, you use post-increment.

更微妙的事情是,由于在使用后增量时没有创建临时值并返回旧值,因此预增量应该永远不会变慢并且可以更快.

The more subtle things are that pre-increment should really never be slower and could be faster due to the lack of creating a temporary and returning the old value when using post-increment.

在 C++ 中使用后增量的一个真实场景是从标准容器中擦除.例如:

A real scenario for using post-increment in C++ is when erasing from standard containers. For example:

set<int> ctr;
ctr.insert(1);
ctr.insert(10);
ctr.insert(12);
ctr.insert(15);

set<int>::iterator it = set.begin();

// Post-increment so the value returned to erase is that of the previous
// iteration (i.e. begin()), yet the iterator stays valid due to the local
// iterator being incremented prior to the erase call
ctr.erase(it++);

// Still valid iterator can be used.
cout << "Value: " << *it << "\n";  

作为对编译器优化的回应,这是正确的,但我认为尽可能准确地传达您要完成的内容总是很重要的.如果您不需要 x++ 的返回值,则不要要求它.另外,如果您的增量类型不是简单类型,我不确定您是否总是会得到相同的优化.想想不仅仅是普通指针的迭代器.在这种情况下,您的里程可能会因优化而异.简而言之,除非您需要后递增运算符的返回值(即旧值),否则始终进行前递增.

In response to the compiler optimization, it is true yet I think it's always important to convey as precisely as possible what you're trying to accomplish. If you don't need the returned value from x++, then don't ask for it. Also, I'm not sure you would always get the same optimization if the type your incrementing is not a simple type. Think iterators that are not just plain pointers. In cases such as this, your mileage may vary with regard to optimization. In short, always pre-increment unless you need the returned (i.e. old value) of the post-increment operator.

这篇关于实际示例中何时使用后递减/递增与前递减/递增?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆