programing tip

C ++ 11 foreach 구문 및 사용자 지정 반복기

itbloger 2020. 12. 8. 07:50
반응형

C ++ 11 foreach 구문 및 사용자 지정 반복기


STL 컨테이너 대신 사용되는 컨테이너에 대한 반복기를 작성 중입니다. 현재 STL 컨테이너는 c ++ 11 foreach 구문 ( 예 : for(auto &x: C). STL 컨테이너를 래핑하는 사용자 지정 클래스를 사용하려면 코드를 업데이트해야합니다.

template< typename Type>
class SomeSortedContainer{
    std::vector<typename Type> m_data; //we wish to iterate over this
    //container implementation code
};    
class SomeSortedContainerIterator{
    //iterator code
};

사용자 지정 컨테이너에 대해 올바른 반복기를 사용하여 코드를 다음과 같은 방식으로 호출 할 수 있도록 자동을 얻으려면 어떻게해야합니까? :

SomeSortedContainer C;
for(auto &x : C){
    //do something with x... 
}

일반적으로 auto가 클래스에 대해 올바른 반복자를 사용하도록하려면 무엇이 필요합니까?


두 가지 선택이 있습니다.

  • 당신은 멤버 함수 이름을 제공 begin하고 end그와 같이 호출 할 수 있습니다 C.begin()C.end();
  • 그렇지 않으면라는 이름의 무료 기능을 제공 begin하고 end그 인수 종속적 조회를 사용하여 발견, 또는 이름 공간에서 할 수있다 std,와 같이 호출 할 수 있습니다 begin(C)end(C).

범위 기반 for를 사용할 수 있으려면 클래스에서 const_iterator begin() constconst_iterator end() const멤버를 제공해야합니다 . 전역 begin함수를 오버로드 할 수도 있지만 멤버 함수가있는 것이 제 생각에는 더 좋습니다. iterator begin()그리고 const_iterator cbegin() const또한 권장하지만, 필요하지 않습니다. 단일 내부 컨테이너에 대해 단순히 반복하려는 경우 정말 쉽습니다.

template< typename Type>
class SomeSortedContainer{

    std::vector<Type> m_data; //we wish to iterate over this
    //container implementation code
public:
    typedef typename std::vector<Type>::iterator iterator;
    typedef typename std::vector<Type>::const_iterator const_iterator;

    iterator begin() {return m_data.begin();}
    const_iterator begin() const {return m_data.begin();}
    const_iterator cbegin() const {return m_data.cbegin();}
    iterator end() {return m_data.end();}
    const_iterator end() const {return m_data.end();}
    const_iterator cend() const {return m_data.cend();}
};    

그래도 사용자 지정 항목을 반복하려면 컨테이너 내부의 클래스로 고유 한 반복기를 디자인해야 할 것입니다.

class const_iterator : public std::iterator<random_access_iterator_tag, Type>{
    typename std::vector<Type>::iterator m_data;
    const_iterator(typename std::vector<Type>::iterator data) :m_data(data) {}
public:
    const_iterator() :m_data() {}
    const_iterator(const const_iterator& rhs) :m_data(rhs.m_data) {}
     //const iterator implementation code
};

반복기 클래스 작성에 대한 자세한 내용은 여기 내 대답을 참조 하십시오 .


As others have stated, your container must implement begin() and end() functions (or have global or std:: functions that take instances of your container as parameters).

Those functions must return the same type (usually container::iterator, but that is only a convention). The returned type must implement operator*, operator++, and operator!=.


To my knowledge SomeSortedContainer just needs to provide begin() and end(). And these should return a standard compliant forward iterator, in your case SomeSortedContainerIterator, which would actually wrap a std::vector<Type>::iterator. With standard compliant I mean it has to provide the usual increment and dereferencing operators, but also all those value_type, reference_type, ... typedefs, which in turn are used by the foreach construct to determine the underlying type of the container elements. But you might just forward them from the std::vector<Type>::iterator.

참고URL : https://stackoverflow.com/questions/7562356/c11-foreach-syntax-and-custom-iterator

반응형