【发布时间】:2011-08-14 10:43:48
【问题描述】:
当然,C++11 中新的 ranged-for 将非常简洁和有用。据我了解它是如何工作的,它通过尝试 *Argument-Depending-Lookup (ADT) 来查找“容器”begin 和 end。
但另一个补充是,所有容器现在都有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