Development Tip

범위 기반 for 루프를 사용할 때 반복기가 필요합니다.

yourdevel 2020. 10. 5. 21:05
반응형

범위 기반 for 루프를 사용할 때 반복기가 필요합니다.


현재 다음과 같이 범위 기반 루프 만 수행 할 수 있습니다.

for (auto& value : values)

그러나 때로는 참조 대신 값에 대한 반복자가 필요합니다 (어떤 이유로 든). 값을 비교하는 전체 벡터를 거치지 않고 방법이 있습니까?


이전 for루프를 다음과 같이 사용하십시오 .

for (auto it = values.begin(); it != values.end();  ++it )
{
       auto & value = *it;
       //...
}

이것으로 당신은 valueiterator뿐만 아니라 it. 사용하고 싶은 것을 사용하십시오.


편집하다:

권장하지는 않지만 범위 기반 for루프 를 사용하려면 (예, 어떤 이유로 든 : D) 다음을 수행 할 수 있습니다.

 auto it = std::begin(values); //std::begin is a free function in C++11
 for (auto& value : values)
 {
     //Use value or it - whatever you need!
     //...
     ++it; //at the end OR make sure you do this in each iteration
 }

이 접근 방식은 항상 동기화되어 value있으므로 주어진 검색을 피 합니다.valueit


다음은 자신의 변수에 별칭을 지정하여 숨겨진 반복기를 노출 할 수있는 프록시 래퍼 클래스입니다.

#include <memory>
#include <iterator>

/*  Only provides the bare minimum to support range-based for loops.
    Since the internal iterator of a range-based for is inaccessible,
    there is no point in more functionality here. */
template< typename iter >
struct range_iterator_reference_wrapper
    : std::reference_wrapper< iter > {
    iter &operator++() { return ++ this->get(); }
    decltype( * std::declval< iter >() ) operator*() { return * this->get(); }
    range_iterator_reference_wrapper( iter &in )
        : std::reference_wrapper< iter >( in ) {}
    friend bool operator!= ( range_iterator_reference_wrapper const &l,
                             range_iterator_reference_wrapper const &r )
        { return l.get() != r.get(); }
};

namespace unpolluted {
    /*  Cannot call unqualified free functions begin() and end() from 
        within a class with members begin() and end() without this hack. */
    template< typename u >
    auto b( u &c ) -> decltype( begin( c ) ) { return begin( c ); }
    template< typename u >
    auto e( u &c ) -> decltype( end( c ) ) { return end( c ); }
}

template< typename iter >
struct range_proxy {
    range_proxy( iter &in_first, iter in_last )
        : first( in_first ), last( in_last ) {}

    template< typename T >
    range_proxy( iter &out_first, T &in_container )
        : first( out_first ),
        last( unpolluted::e( in_container ) ) {
        out_first = unpolluted::b( in_container );
    }

    range_iterator_reference_wrapper< iter > begin() const
        { return first; }
    range_iterator_reference_wrapper< iter > end()
        { return last; }

    iter &first;
    iter last;
};

template< typename iter >
range_proxy< iter > visible_range( iter &in_first, iter in_last )
    { return range_proxy< iter >( in_first, in_last ); }

template< typename iter, typename container >
range_proxy< iter > visible_range( iter &first, container &in_container )
    { return range_proxy< iter >( first, in_container ); }

용법:

#include <vector>
#include <iostream>
std::vector< int > values{ 1, 3, 9 };

int main() {
    // Either provide one iterator to see it through the whole container...
    std::vector< int >::iterator i;
    for ( auto &value : visible_range( i, values ) )
        std::cout << "# " << i - values.begin() << " = " << ++ value << '\n';

    // ... or two iterators to see the first incremented up to the second.
    auto j = values.begin(), end = values.end();
    for ( auto &value : visible_range( j, end ) )
        std::cout << "# " << j - values.begin() << " = " << ++ value << '\n';
}

I tried myself on this and found a solution.

Usage:

for(auto i : ForIterator(some_list)) {
    // i is the iterator, which was returned by some_list.begin()
    // might be useful for whatever reason
}

The implementation was not that difficult:

template <typename T> struct Iterator {
    T& list;
    typedef decltype(list.begin()) I;

    struct InnerIterator {
        I i;
        InnerIterator(I i) : i(i) {}
        I operator * () { return i; }
        I operator ++ () { return ++i; }
        bool operator != (const InnerIterator& o) { return i != o.i; }
    };

    Iterator(T& list) : list(list) {}
    InnerIterator begin() { return InnerIterator(list.begin()); }
    InnerIterator end() { return InnerIterator(list.end()); }
};
template <typename T> Iterator<T> ForIterator(T& list) {
    return Iterator<T>(list);
}

range based for loop is created as the c++ counterpart for foreach in java that allows easy iteration of array elements. It is meant for removing the usage of complex structures like iterators so as to make it simple. I you want an iterator, as Nawaz said, you will have to use normal for loop.


There is a very simple way of doing this for std::vector, which should also work if you are resizing the vector during the process (I'm not sure whether the accepted answer considers this case)

If b is your vector, you can just do

for(auto &i:b){
    auto iter = b.begin() + (&i-&*(b.begin()));
}

where iter will be your required iterator.

This takes advantage of the fact that C++ vectors are always contiguous.


Let's do it very dirty ... I know, the 0x70h is changing with stack-usage, compiler version, .... It should be exposed by the compiler, but it is not :-(

char* uRBP = 0; __asm { mov uRBP, rbp }
Iterator** __pBegin = (Iterator**)(uRBP+0x70);
for (auto& oEntry : *this) {
    if (oEntry == *pVal) return (*__pBegin)->iPos;
}

참고URL : https://stackoverflow.com/questions/6953128/need-iterator-when-using-ranged-based-for-loops

반응형