My workmate claims that for object types preincrement is more efficient than post increment
e.g.
std::vector<std::string> vec; ... insert a whole bunch of strings into vec ... // iterate over and do stuff with vec. Is this more efficient than the next // loop? std::vector<std::string>::iterator it; for (it = vec.begin(); it != vec.end(); ++it){ } // iterate over and do stuff with vec. Is this less efficient than the previous loop? std::vector<std::string>::iterator it; for (it = vec.begin(); it != vec.end(); it++){ }
Iterator and for-each loop are faster than simple for loop for collections with no random access, while in collections which allows random access there is no performance change with for-each loop/for loop/iterator.
The main advantage of an iterator is to provide a common interface for all the containers type. Iterators make the algorithm independent of the type of the container used. Iterators provide a generic approach to navigate through the elements of a container.
The primary purpose of an iterator is to allow a user to process every element of a container while isolating the user from the internal structure of the container. This allows the container to store elements in any manner it wishes while allowing the user to treat it as if it were a simple sequence or list.
An iterator is an object that can iterate over elements in a C++ Standard Library container and provide access to individual elements.
Postincrement must return the value the iterator had BEFORE it was incrementing; so, that previous value needs to be copied somewhere before altering it with the increment proper, so it's available to return. The extra work may be a little or a lot, but it certainly can't be less than zero, compared to a preincrement, which can simply perform the incrementing and then return the just-altered value -- no copying // saving // etc necessary.
So, unless you specifically MUST have postincrement (because you're using the "value before increment" in some way), you should always use preincrement instead.
The default increment operators will look like this:
class X { X operator++(int) // Post increment { X tmp(*this); this->operator++(); // Call pre-increment on this. return tmp; } X& operator++() // Pre increment { // Do operation for increment. return *this; } };
Notice the Post-increment is defined in terms of the Pre-increment. So Post-increment does the same work plus some extra. Usually this is construct a copy and then return the copy via a copy (Note the Pre-increment can return itself by reference but the Post-increment can not).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With