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

除常规数组外,函数 reverse_sort 支持任何类型的容器,因为它调用 begin() 的非成员版本。 如果将 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