2017-05-13 2 views
-2

여러 다른 장소에서 반복 패턴을 구현하는 나는 다음과 같은 패턴이 내 코드에서 여러 다른 장소에서 반복이 : m_condition, m_vectorm_index 반원 있습니다더 좋은 방법은 코드

if (m_condition) 
{ 
    auto& item = m_vector[m_index]; 
    // Do something with 'item' 
} 
else 
{ 
    for (auto& item : m_vector) 
    { 
     // Do something with 'item' 
    } 
} 

.

Do something with 'item' 부분은 패턴이 나타날 때마다 다릅니다.

성능을 향상시키는 데있어 더 좋고/더 깔끔하게/더 짧은 방법을 찾고 있습니다.

나는이 함께했다,하지만 좀 "불쾌한"느낌 :

auto iBgnIndex = m_condition ? m_index : 0; 
auto iEndIndex = m_condition ? m_index : m_vector.size()-1; 
for (auto i = iBgnIndex; i <= iEndIndex; i++) 
{ 
    // Do something with 'm_vector[i]' 
} 

더 나은 어떤 옵션이 있습니까?

감사

+0

당신은 그걸 자신의 함수로 추출 할 수 없습니까? – user2296177

+0

@ user2296177 : 정확히 무엇을 의미합니까? – goodvibration

+0

첫 번째 코드 블록을 적절한 매개 변수가있는 함수 안에 넣은 다음 해당 패턴을 사용할 때마다 호출하십시오. 당신의'// something 'with something'은 호출 가능한 매개 변수가 될 수 있습니다. – user2296177

답변

1

반복되는 패턴이 유형의 가장 약간 더 구체적인 맥락에서 해결되기 때문이 까다 롭습니다. 이 "하나 또는 모든 것"중 하나를 수행하는 것은 일반적으로 읽기 쉽게 작성하기가 어렵습니다. 여기

template <typename IndexedContainer_, typename UnaryOp_> 
void apply_for_index(const IndexedContainer_& c, int index, UnaryOp_ op) 
{ 
    if (index == -1) 
     for (auto& elem : c) op(elem); 
    else 
     op(c[index]); 
} 

template <typename ForwardContainer_, typename Iterator_, typename UnaryOp_> 
void apply_for_iter(const ForwardContainer_& c, Iterator_ it, UnaryOp_ op) 
{ 
    if (it == c.end()) 
     for (auto& elem : c) op(elem); 
    else 
     op(*it); 
} 

:

말했다되고 그건

은 여기 (편의를 위해) 지수 및 사용자 정의 또는 표준 반복자와 함께 귀하의 경우에 작동하는 솔루션입니다 (여기 선명도에 대한 int으로 인덱스를 harcoded) 당신이 볼 수 있듯이이 수준에서 문제를 해결할 때

int main(int argc, char *argv[]) 
{ 
    std::vector<int> elems = {0, 1, 2, 3, 4, 5}; 

    printf("All:\n"); 

    bool cond = false; 
    int four_or_all = cond ? 4 : -1; 
    apply_for_index(elems, four_or_all, [](int elem) { 
     printf("elem=%d\n", elem); 
    }); 

    printf("\nSpecifically 4:\n"); 

    four_or_all = !cond ? 4 : -1; 
    apply_for_index(elems, four_or_all, [](int elem) { 
     printf("elem=%d\n", elem); 
    }); 

    printf("\nAll with iterators:\n"); 

    auto four_or_all_iter = cond ? elems.begin() + 4 : elems.end(); 
    apply_for_iter(elems, four_or_all_iter, [](int elem) { 
     printf("elem=%d\n", elem); 
    }); 

    printf("\nSpecifically 4 with iterators:\n"); 

    four_or_all_iter = !cond ? elems.begin() + 4 : elems.end(); 
    apply_for_iter(elems, four_or_all_iter, [](int elem) { 
     printf("elem=%d\n", elem); 
    }); 

    return 0; 
} 

이, 당신이 읽기 어려울 수 있습니다 플래그 또는 감시 값의 어떤 종류를 사용하게 : 몇 가지 예를 사용합니다.

+0

고맙습니다 ...... – goodvibration

+0

@goodvibration 문제를 해결 한 경우 upvote하고 대답을 수락하십시오. – user2296177

+0

나는 내가 이미 가지고있는 것보다 더 청결한/더 짧은 것을 찾고 있기 때문에 upvoted, 그러나 받아들이지 않았다. – goodvibration

관련 문제