何时使用std :: begin和std :: end而不是容器特定的版本 [英] When to use std::begin and std::end instead of container specific versions

查看:139
本文介绍了何时使用std :: begin和std :: end而不是容器特定的版本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有任何一般偏好或规则解释应该使用容器特定版本的begin和end而不是自由函数 std :: begin std :: end

Are there any general preferences or rules that explain when container specific versions of begin and end should be used instead of free functions std::begin and std::end?

这是我的理解,如果函数是一个模板,容器类型是一个模板参数,应使用c $ c> std :: begin 和 std :: end ,即:

It is my understanding that if the function is a template whereby the container type is a template parameter then std::begin and std::end should be used, i.e.:

template<class T> void do_stuff( const T& t )
{
    std::for_each( std::begin(t), std::end(t), /* some stuff */ );
}

在其他情况下如标准/成员函数,容器是什么?是更好的做法是使用 std :: begin(cont) std :: end(cont)首选容器的成员函数 cont.begin() cont.end()

What about in other scenarios such as a standard / member function where the type of container is known? Is it still better practice to use std::begin(cont) and std::end(cont) or should the container's member functions cont.begin() and cont.end() be preferred?

我通过调用 cont.end()超过 std来假定性能没有好处, :end(cont)

推荐答案

c $ c> std :: begin :

If you look at, say, the definition of std::begin:

template< class C > 
auto begin( C& c ) -> decltype(c.begin());

你看到它所做的就是引用 begin c $ c>反正。我认为一个体面的编译器会使差异为零,所以我想它归结为偏好。就我个人而言,我会使用 cont.begin() cont.end()必须向任何人解释:)

You see that all it does is reference the begin() anyway. I suppose a decent compiler will make the difference nil, so I guess it comes down to preference. Personally, I'd use cont.begin() and cont.end() just so that I wouldn't have to explain it to anybody :)

然而,Mooing Duck指出, std :: begin 在数组上:

As Mooing Duck points out, however, std::begin also works on arrays:

template< class T, size_t N > 
T* begin( T (&array)[N] );

...因此需要考虑。如果你不是使用数组,我会与我的建议。但是如果你不确定传递的是STL容器,还是数组< T> ,那么 std :: begin ()是要走的路。

... so there is that to consider. If you are not using arrays, I'd go with my suggestion. However if you are unsure if what is passed is going to be an STL container, or an array of <T>, then std::begin() is the way to go.

这篇关于何时使用std :: begin和std :: end而不是容器特定的版本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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