【问题标题】:When should I use the new ranged-for and can I combine it with the new cbegin/cend?我应该什么时候使用新的 ranged-for,我可以将它与新的 cbegin/cend 结合使用吗?
【发布时间】:2011-08-14 10:43:48
【问题描述】:

当然,C++11 中新的 ranged-for 将非常简洁和有用。据我了解它是如何工作的,它通过尝试 *Argument-Depending-Lookup (ADT) 来查找“容器”beginend

但另一个补充是,所有容器现在都有cbegin()cend() 来获取容器的const_iterators

我有点困惑,一方面我想我应该使用cbegin(),如果我这样做想要修改容器,另一方面我必须添加一个额外的@987654327 @ 在 ranged-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()

编辑:更正错误Value vs Iterator

【问题讨论】:

    标签: c++ for-loop c++11 foreach idioms


    【解决方案1】:

    cbegin() 允许您从非const 容器中获取const_iterators,而无需显式转换或转换。如果你有一个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);
    

    【讨论】:

    • 是的。那么对于 non-const 容器 v const auto it1 = v.begin() auto it2 = v.cbegin() 相同吗?第一个是const iterator it,第二个是const_iterator it。这些是不同的类型,我可以++it1,因为迭代器本身是const,对吧?
    【解决方案2】:

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

    这还不是惯用的,因为新标准甚至还没有出版!

    【讨论】:

      猜你喜欢
      • 2012-03-18
      • 1970-01-01
      • 1970-01-01
      • 2011-01-18
      • 2011-08-18
      • 2017-03-21
      • 2011-02-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多