What is the reason behind cbegin/cend?(cbegin/cend 背后的原因是什么?)
问题描述
我想知道为什么在 C++11 中引入了 cbegin 和 cend ?
I wonder why cbegin and cend were introduced in C++11?
在哪些情况下调用这些方法与 begin 和 end 的 const 重载有区别?
What are cases when calling these methods makes a difference from const overloads of begin and end?
推荐答案
很简单.假设我有一个向量:
It's quite simple. Say I have a vector:
std::vector<int> vec;
我用一些数据填充它.然后我想得到一些迭代器.也许让他们四处走动.也许到 std::for_each:
I fill it with some data. Then I want to get some iterators to it. Maybe pass them around. Maybe to std::for_each:
std::for_each(vec.begin(), vec.end(), SomeFunctor());
在 C++03 中,SomeFunctor 可以自由地修改它获得的参数.当然,SomeFunctor 可以按值或按const& 获取其参数,但没有办法确保 这样做.并非没有做这样愚蠢的事情:
In C++03, SomeFunctor was free to be able to modify the parameter it gets. Sure, SomeFunctor could take its parameter by value or by const&, but there's no way to ensure that it does. Not without doing something silly like this:
const std::vector<int> &vec_ref = vec;
std::for_each(vec_ref.begin(), vec_ref.end(), SomeFunctor());
现在,我们介绍cbegin/cend:
std::for_each(vec.cbegin(), vec.cend(), SomeFunctor());
现在,我们有句法保证,即 SomeFunctor 不能修改向量的元素(当然,没有 const-cast).我们明确地得到 const_iterator,因此 SomeFunctor::operator() 将被 const int & 调用.如果它的参数是int &,C++会报编译错误.
Now, we have syntactic assurances that SomeFunctor cannot modify the elements of the vector (without a const-cast, of course). We explicitly get const_iterators, and therefore SomeFunctor::operator() will be called with const int &. If it takes it's parameters as int &, C++ will issue a compiler error.
C++17 对此问题有更优雅的解决方案:std::as_const.好吧,至少在使用基于范围的 for 时它很优雅:
C++17 has a more elegant solution to this problem: std::as_const. Well, at least it's elegant when using range-based for:
for(auto &item : std::as_const(vec))
这只是返回一个 const& 给它提供的对象.
This simply returns a const& to the object it is provided.
这篇关于cbegin/cend 背后的原因是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:cbegin/cend 背后的原因是什么?
基础教程推荐
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 我有静态或动态 boost 库吗? 2021-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 常量变量在标题中不起作用 2021-01-01
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 这个宏可以转换成函数吗? 2022-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
