我应该在什么时候使用新的range -for,以及我可以将它与新的cbegin/cend结合使用吗?

When should I use the new ranged-for and can I combine it with the new cbegin/cend?

本文关键字:cbegin cend 结合 range 什么时候 -for 我应该 我可以      更新时间:2023-10-16

c++ 11中新的range -for当然会非常简洁和有用。据我所知,它是如何工作的,它通过尝试"参数依赖查找"(ADT)来查找"容器" beginend

但另一个额外的是,所有的容器现在有cbegin()cend() 为容器获得const_iterators

我有点困惑,一方面,我想我应该使用cbegin(),如果我做想修改容器,另一方面,我必须在范围内添加额外的const -for以获得同样的东西。

所以,它看起来像这样:

// print all
for(const auto elem : data)
  cout << elem

使用ADT,找到data.begin(),因此需要const

// print everything but the first (a reason not to use range-for)
for(auto it = data.cbegin()+1; it!=data.cend(); ++it)
  cout << *it

使用data.cbegin(),因此不需要const

但是这不是更"习惯"吗?:

// print everything but the first (a reason not to use range-for)
for(const auto it = data.begin()+1; it!=data.end(); ++it)
  cout << *it
  • 我把"习语"理解对了吗?添加吗?
  • 何时使用cbegin ?
  • 我错过了范围的东西,只寻找begin()吗?

Edit:更正错误Value vs Iterator

cbegin()允许您从非const容器中获得const_iterator s,而无需显式强制转换或转换。如果你有一个const容器,那么begin()无论如何都会返回一个const_iterator

新的for结构使用begin(),因为这是最通用的,它避免了太多的特殊情况。此外,默认情况下,该变量是,而不是迭代器或引用。

std::vector<int> v;
for(auto i: v) // i is an int
    dostuff(i);

这避免了在复制元素时修改容器的问题。要获取引用,需要声明它:

for(auto &i: v)
    dostuff(i);

如果不打算修改范围内的元素,我会在for循环中使用cbegin/cend in。这就是首先添加它们的明显原因。

这很难说是习惯用语,因为新标准甚至还没有出版!