我应该在什么时候使用新的range -for,以及我可以将它与新的cbegin/cend结合使用吗?
When should I use the new ranged-for and can I combine it with the new cbegin/cend?
c++ 11中新的range -for当然会非常简洁和有用。据我所知,它是如何工作的,它通过尝试"参数依赖查找"(ADT)来查找"容器" begin
和end
。
但另一个额外的是,所有的容器现在有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。这就是首先添加它们的明显原因。
这很难说是习惯用语,因为新标准甚至还没有出版!
相关文章:
- 为什么 std::span 缺少 cbegin 和 cend 方法?
- begin() 在 C++17 年被制作为 constexpr 但在 C++14 年成为 cbegin() 吗?
- 如何实现 cbegin() 和 cend() 从 begin() 和 end() ?
- 在载体中使用cbegin和cend
- 无法在 cbegin 中定义initializer_list
- begin(),end()和cbegin(),cend()之间的区别是什么?
- 是cbegin/Cend不足以使循环范围
- 为什么 std::cbegin() 不调用容器上的 .cbegin()?
- 'cbegin'未在此范围内声明
- std::cbegin()除了begin()之外还有其他内容吗
- 为什么std::cbegin返回与std::begin相同的类型
- cbegin/cend背后的原因是什么
- 非成员函数 begin()/cbegin() 及其 constexpr-ness
- 为什么我不能将 cend() 和 cbegin() 传递给count_if?
- gcc支持cbegin和cend方法
- cbegin()/cend() vs constBegin()/constEnd()
- 为什么 g++ 声明某些 valarray o 存在"no matching function for call cbegin(o)"<double>?
- 在基于范围的for中强制使用cbegin()/cend()
- 我应该在什么时候使用新的range -for,以及我可以将它与新的cbegin/cend结合使用吗?
- 既然有了cbegin(), cend(),为什么没有cfront(), cback(), cfind(),…