5. Range-based for(c++11)

一般形式:

for( decl : coll)
{
   Statement;
}

可以将vector vec中的各个元素乘3。

std::vector<double> vec;
...
for ( auto& elem : vec ) 
{
    elem *= 3;
}

以下两种情况表示的是同一种操作:

for ( decl : coll )
{
    //statement
}

for (auto _pos=coll.begin(), _end=coll.end(); _pos!=_end; ++_pos )
{
    decl = *_pos;
    Statement
}
//如果不满足上面的那种,那么便可以用下面的形式表示:
for (auto _pos=begin(coll), _end=end(coll); _pos!=_end; ++_pos ) 
{
    decl = *_pos;
    statement
}

而且你也可以使用寻常的固定大小的C风格数组:

int array[] = { 1, 2, 3, 4, 5 };
long sum=0; // process sum of all elements
for (int x : array)
{
    sum += x;
}

for (auto elem : { sum, sum*2, sum*4 } )
{ 
    std::cout << elem << std::endl;
}
//输出:15,30,60

但是当构造函数被explicit修饰的时候,下面这样就不被允许:

class C
{
    public:
    explicit C(const std::string& s){...}; // explicit(!) type conversion from strings
};
...
std::vector<std::string> vs;
for (const C& elem : vs)  // ERROR, no conversion from string to C defined
{ 
   ...
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值