共用方式為


begin

擷取在指定的容器中第一個項目的迭代器。

template<class Container>
    auto begin(Container& cont)
        -> decltype(cont.begin());
template<class Container>
    auto begin(const Container& cont) 
        -> decltype(cont.begin());
template<class Ty, class Size>
    Ty *begin(Ty (&array)[Size]);

參數

  • cont
    容器。

  • array
    Ty 類型的物件陣列。

傳回值

前兩個樣板函式會傳回 cont.begin()。 第一個函式是非常數,第二個是常數。

第三個樣板函式會傳回 array。

範例

需要更泛型的行為時,建議您使用這個樣板函式取代容器成員 begin()

// cl.exe /EHsc /nologo /W4 /MTd 
#include <algorithm>
#include <functional>
#include <iostream>
#include <iterator>
#include <vector>

template <typename C> void reverse_sort(C& c) {
    using std::begin;
    using std::end;

    std::sort(begin(c), end(c), std::greater<>());
}

template <typename C> void print(const C& c) {
    for (const auto& e : c) {
        std::cout << e << " ";
    }

    std::cout << "\n";
}

int main() {
    std::vector<int> v = { 11, 34, 17, 52, 26, 13, 40, 20, 10, 5, 16, 8, 4, 2, 1 };

    print(v);
    reverse_sort(v);
    print(v);

    std::cout << "--\n";

    int arr[] = { 23, 70, 35, 106, 53, 160, 80, 40, 20, 10, 5, 16, 8, 4, 2, 1 };

    print(arr);
    reverse_sort(arr);
    print(arr);
}
Output:
11 34 17 52 26 13 40 20 10 5 16 8 4 2 1
52 40 34 26 20 17 16 13 11 10 8 5 4 2 1
--
23 70 35 106 53 160 80 40 20 10 5 16 8 4 2 1
160 106 80 70 53 40 35 23 20 16 10 8 5 4 2 1

因為它會呼叫非成員版本的 begin(),除了標準陣列之外,reverse_sort 函式支援任何種類的容器。 如果 reverse_sort 編使用容器成員 begin()

template <typename C> void reverse_sort(C& c) {
    using std::begin;
    using std::end;

    std::sort(c.begin(), c.end(), std::greater<>());
}

將陣列傳給它,會導致這個編譯器錯誤:

error C2228: left of '.begin' must have class/struct/union

需求

標頭:<iterator>

命名空間: std

請參閱

參考

<iterator>

cbegin

cend

end