Concept difference between pre and post increment operator for STL

后端 未结 5 1441
再見小時候
再見小時候 2020-12-19 04:44

Supposedly:

for (vector::iterator iter = ivec.begin(); iter != ivec.end(); ++iter)
{}

I do understand the difference when it com

5条回答
  •  佛祖请我去吃肉
    2020-12-19 05:42

    It all depends on how they are implemented.

    But the most common way implementation of post increment is in terms of pre-increment with an extra copy.

    class MyIter
    {
        // Definition of pre-increment:
        //    ++object;
        MyIter& operator++()
        {
            /* Increment the iterator as appropriate
               You should be changing the object in place
             */
    
    
            // Once you are done return yourself.
            return *this;
        }
        // Definition of post-increment:
        //    object++;
        MyIter operator++(int)
        {
            // Post increment (returns the same value) so build the result.
            MyIter  result(*this);
    
            // Now do the increment using pre-increment on the current object
            ++(*this);
    
            // return the result.
            return result;
        }
    };
    

    So the standard implementation of post increment calls pre-increment and in addition makes a copy of the object. Note there is also an additional copy construction on return but this is usually illeded by the compiler.

    Note pre-increment because it affects the same obejct usually returns a reference to itslef (so not cost on the return).

提交回复
热议问题