The new 范围为当然,在 C++11 中会非常简洁和有用。据我了解它是如何工作的,它会查找“容器”begin
and end
通过尝试*Argument-Depending-Lookup”(ADT)。
但另一个补充是所有容器现在有cbegin()
and cend()
得到const_iterators
对于容器。
我有点困惑,一方面我想我应该使用cbegin()
如果我做not想要修改容器,另一方面我必须添加一个额外的const
在 - 的里面范围为得到同样的东西。
所以,它看起来像这样:
// print all
for(const auto elem : data)
cout << elem
使用ADT,找到data.begin(),因此const
needed.
vs
// print everything but the first (a reason not to use range-for)
for(auto it = data.cbegin()+1; it!=data.cend(); ++it)
cout << *it
using data.cbegin()
,因此没有const
needed.
但这不是更“惯用”吗?:
// 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()
only?
Edit:纠正错误值与迭代器
cbegin()
让你得到const_iterator
s 来自非const
没有显式强制转换或转换的容器。如果你有一个const
然后容器begin()
将返回一个const_iterator
anyway.
The new for
构造用途begin()
因为这是最普遍的,它避免了太多的特殊情况。另外,默认情况下,该变量是value,不是迭代器或引用。
std::vector<int> v;
for(auto i: v) // i is an int
dostuff(i);
这避免了在复制元素时修改容器的问题。要获取引用,您需要声明它:
for(auto &i: v)
dostuff(i);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)