为什么在C ++ 11中使用非成员开始和结束函数? [英] Why use non-member begin and end functions in C++11?

查看:122
本文介绍了为什么在C ++ 11中使用非成员开始和结束函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

每个标准容器都有一个 begin end 函数,用于返回该容器的迭代器。但是,C ++ 11显然引入了一些免费函数,名为 begin end 调用 begin end 成员函数。所以,而不是写

Every standard container has a begin and end function for returning iterators for that container. However, C++11 has apparently introduced free functions called begin and end which call the begin and end member functions. So, instead of writing

auto i = v.begin();
auto e = v.end();

您可以写

auto i = begin(v);
auto e = 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.

所以,问题是什么是自由功能版本 begin end 不能调用其相应的成员函数版本,为什么要使用它们? / p>

So, the question is what exactly do the free function versions of begin and end do beyond calling their corresponding member function versions, and why would you want to use them?

推荐答案

如何调用 .begin() .end()在C数组上?

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中使用非成员开始和结束函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆