2012-09-26 9 views
2

STL 반복기를 다시 사용하려고 시도했지만 이에 대한 정보를 찾을 수 없습니다. 이 코드에있어 문제 :STL 반복자 재설정

std::vector< boost::shared_ptr<Connection> >::iterator poolbegin = pool.begin(); 
std::vector< boost::shared_ptr<Connection> >::iterator poolend = pool.end(); 
if(order) { 
    poolbegin = pool.rbegin(); // Here compilation fails 
    poolend = pool.rend(); 
} 
    for(std::vector< boost::shared_ptr<Connection> >::iterator it = poolbegin; it<poolend; it++) { 

그러나 점점 오류 :

error: no match for ‘operator=’ in ‘poolbegin = std::vector<_Tp, _Alloc>::rbegin() with _Tp = boost::shared_ptr, _Alloc = std::allocator >’

새로운 값으로 반복자를 재설정 할 수있는 방법이 있습니까? shared_ptr :: reset처럼?

+4

반복자를 반복자는 다른, 관련이없는 종류 역. –

답변

1

일부 조건에 따라 벡터를 앞뒤로 이동하는 루프가 필요합니다.

이 작업을 수행하는 한 가지 방법은 루프 바디를 펑터 (또는 C++ 11을 사용하는 경우 람다)로 분해하는 것입니다.

struct LoopBody { 
    void operator()(boost::shared_ptr<Connection> connection) { 
    // do something with the connection 
    } 
    // If the loop body needs to be stateful, you can add a constructor 
    // that sets the initial state in member variables. 
}; 

지금 당신은 당신이 루프를 통과 할 방법을 두 가지 대안이있을 수 있습니다 :

LoopBody loop_body; 
if (reverse_order) { 
    std::for_each(pool.rbegin(), pool.rend(), loop_body); 
} else { 
    std::for_each(pool.begin(), pool.end(), loop_body); 
} 
7

rbegin()은 과 완전히 다른 유형 인 reverse_iterator을 반환합니다.

서로 할당 할 수 없습니다.