2013-10-09 3 views
1

입력 및 출력 반복기 사용에 관한 실제 질문이 있습니다. 함수의 제목은 다음과 같습니다.입력 및 출력 반복기

template<class InpIter,class OutpIter> 
OutpIter my_unique_copy(InpIter first, InpIter last, OutpIter result) 

이 함수는 [first, last] 범위의 요소를 결과로 복사해야합니다. 연속되는 중복 요소 그룹에서 첫 번째 값만 복사됩니다. 반환 값은 요소가 복사되는 범위의 끝입니다. 복잡성 : 선형

나는 아직 나는 이것이 당신이,가는 있었는지 생각

template<class InpIter,class OutpIter> 
OutpIter my_unique_copy(InpIter first, InpIter last, OutpIter result){ 
    InpIter current=first; 
    first++;//point to second element 
    while(first!=last){ 
     while(*first==*current){//Keep comparing elements to current to see if they're same 
      first++; 
     } 
     result=current; 
     current=first; 
     result++; 
     first++; 
    } 
    return result; 
} 
+1

그래, 뭐가 문제 야? :) – jrok

+3

컴파일러는 물지 않습니다. 편안하게 접근하는 유일한 방법은 시도해 보는 것입니다. – Cogwheel

+0

또한 'unique_copy()'를 사용할 수도 있습니다 – Kunal

답변

0

반복자와 그 불편 해요 이후 조금 도움이 궁금 할 어떤 아이디어가 각 단계에서 설명.

template<class InpIter,class OutpIter> 
OutpIter my_unique_copy(InpIter first, InpIter last, OutpIter result) 
{ 
    // keep going until end of sequence 
    while(first!=last) 
    { 
     // save current position. 
     InpIter current=first; 

     // advance first, test it against last, and if not 
     // equal, test what it references against current. 
     // repeat this until *first != *current, or first == last 
     while (++first != last && *first == *current); 

     // not matter what dropped the loop above, we still have 
     // our current, so save it off and advance result. 
     *result++ = *current; 
    } 

    // not sure why you want to return the first iterator position 
    // *past* the last insertion, but I kept this as-is regardless. 
    return result; 
} 

나는 그것을 설명하기를 바랍니다. (내가 놓친 생각하지 않지만, 내가 그랬다면 내가 듣게 될 것입니다 확신합니다.)

아주 간단한 테스트 하네스 :

#include <iostream> 
#include <iterator> 
#include <algorithm> 

int main() 
{ 
    int ar[] = { 1,2,2,3,3,3,4,5,5,6,7,7,7,7,8 }; 
    int res[10] = {0}; 

    int *p = my_unique_copy(std::begin(ar), std::end(ar), res); 
    std::copy(res, p, std::ostream_iterator<int>(std::cout, " ")); 
    return 0; 
} 

출력을

1 2 3 4 5 6 7 8 
+0

굉장해! 나는 반환에 대해 확신하지 못했지만 그게 사양으로 들리는 것처럼 들렸습니다. 마지막으로, while 루프 내에서 우리가 처음으로 증가 할 것이라고 추측하면 더 이상 현재 값을 저장하지 않고 다음 값으로 시작할 수 있습니다. –

+0

나는 그 마지막 것을 따랐는지 확신하지 못합니다. 나는 inner-while-loop 논리가 어떻게 작동하는지 설명하려고 노력했다. 우리가 아직 '마지막'이 아니라는 것을 알지 못한다면 부울 - 단락 회로 평가를 사용하여 '처음'을 배제하지 않습니다. 정확한 순서는 1. '첫 번째'를 증가시키고, 2. 그것이 '마지막'인지 확인합니다. 3.'* first == * current'가 같지 않으면 깨져 있는지 확인하십시오. 그렇지 않으면 1로 돌아가십시오. – WhozCraig

+0

그리고'* result'를 저장 한 후에'current'를 처음으로 리셋하지 않고 이것이 어떻게 작동하는지 궁금하다면, 그것을 저장하는 것이 무엇이겠습니까? 우리는 이것을 할 것입니다 :'current = first'. 하지만 정확히 위의 코드 *가 inner-while-loop에서하는 것입니다. 그리고 다시 실행될 것입니다 ('first == last'가 아니면). – WhozCraig