问题描述
每个标准容器都有一个 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 中使用非成员开始和结束函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!