Why use non-member begin and end functions in C++11?(为什么在 C++11 中使用非成员开始和结束函数?)
问题描述
每个标准容器都有一个 begin
和 end
方法,用于返回该容器的迭代器.但是,C++11 显然引入了名为 std::begin代码> 和
std::end
调用 begin
和 end
成员函数.所以,而不是写
Every standard container has a begin
and end
method for returning iterators for that container. However, C++11 has apparently introduced free functions called std::begin
and std::end
which call the begin
and end
member functions. So, instead of writing
auto i = v.begin();
auto e = v.end();
你会写
auto i = std::begin(v);
auto e = std::end(v);
在编写现代 C++ 的演讲中,Herb Sutter 说当您想要容器的开始或结束迭代器时,您现在应该始终使用自由函数.但是,他没有详细说明为什么你会想要.查看代码,它为您节省了一个字符.因此,就标准容器而言,免费功能似乎完全无用.Herb Sutter 表示非标准容器有好处,但同样,他没有详细说明.
In his talk, Writing Modern C++, Herb Sutter says that you should always use the free functions now when you want the begin or end iterator for a container. However, he does not go into detail as to why you would want to. Looking at the code, it saves you all of one character. So, as far as the standard containers go, the free functions seem to be completely useless. Herb Sutter indicated that there were benefits for non-standard containers, but again, he didn't go into detail.
那么,问题是 std::begin
和 std::end
的自由函数版本除了调用它们对应的成员函数版本之外究竟做了什么,以及为什么你想使用它们吗?
So, the question is what exactly do the free function versions of std::begin
and std::end
do beyond calling their corresponding member function versions, and why would you want to use them?
推荐答案
你如何在 C 数组上调用 .begin()
和 .end()
?
How do you call .begin()
and .end()
on a C-array ?
自由函数允许更通用的编程,因为它们可以在之后添加到您无法更改的数据结构上.
Free-functions allow for more generic programming because they can be added afterwards, on a data-structure you cannot alter.
这篇关于为什么在 C++11 中使用非成员开始和结束函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么在 C++11 中使用非成员开始和结束函数?
基础教程推荐
- Windows Media Foundation 录制音频 2021-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 使用从字符串中提取的参数调用函数 2022-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 从 std::cin 读取密码 2021-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01