다음을 통해 공유


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