STL ++iter与iter++区别

转:https://blog.csdn.net/specialsun/article/details/84922373

 

之前编码一直用的是iter++,同事说该方式效率比较低。带着疑惑看STL源码:

 

// vector
 
_Myiter& operator++()
    {    // preincrement
    ++*(_Mybase *)this;
    return (*this);
    }
 
_Myiter operator++(int)
    {    // postincrement
    _Myiter _Tmp = *this;
    ++*this;
    return (_Tmp);
    }


 

果不其然,++iter 前向表达式返回引用,而iter++返回的却是一临时对象。

原来前向后向重载表达式的差异,只是多了一个int参数。

 

// Test
class Test
{
public:
        Test():val(0){}
        ~Test(){}
 
        Test &operator++()
        {
                ++val;
                printf("Pre incr val:%d\n", val);
                return (*this);
        }
 
        Test operator++(int)
        {
                Test pTmp = *this;              // save
                val++;
                printf("Post incr val:%d\n", val);
                return pTmp;
        }
 
private:
        int val;
};
 
// main
int main()
{
        Test test;
        test++;
        ++test;
        return 0;
}


 

输出:

Post incr val:1

Pre incr val:2

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值