Difference between vector::begin() and std::begin()

后端 未结 2 1916
生来不讨喜
生来不讨喜 2020-12-13 07:02

While iterating over a vector in c++, I noticed there is a begin() function in the standard library, and also a begin() as a member function of the

相关标签:
2条回答
  • 2020-12-13 07:20

    The implementation of std::begin() for vectors simply calls std::vector<T>::begin(), so there is no difference between the two in this exact case.

    Where std::begin() comes into its own is in generic algorithms:

    template<typename Container>
    void my_algorithm(Container c) {
        using std::begin;
        using std::end;
        auto const start = begin(c);  // ADL will find the appropriate overload
        auto const finish = end(c);
        // ... rest of code ...
    }
    
    0 讨论(0)
  • 2020-12-13 07:27

    std::begin() was added in C++11 to make it easier to write generic code (e.g. in templates). The most obvious reason for it is that plain C-style arrays do not have methods, hence no .begin(). So you can use std::begin() with C-style arrays, as well as STL-style containers having their own begin() and end().

    If you're writing code which is not a template, you can ignore std::begin(); your fellow programmers would probably find it odd if you suddenly started using it everywhere just because it's new.

    0 讨论(0)
提交回复
热议问题