2016-10-17 2 views
0

copy_if 필터를 사용하는 방법은 인덱스의 특정 배수를 str으로 필터링하는 것입니다.`copy_if` 필터를 사용하여 인덱스의 특정 배수를 필터링하십시오.

str은 "1000020000300004000050000"이고, newStr은 "12345"입니다. 1 따르면

35 * 2


소스 코드, 5 * 0, 25 * 1이다 :

std::string str("1000020000300004000050000"); 
std::string newStr; 

std::copy_if(str.begin(), str.end(), 
    std::back_inserter(newStr), 
    [] (char c) { 
     // Some specific rule I want to return. 
     return ...; 
    } 
); 

이상적인 코드 :

std::copy_if(str.begin(), str.end(), 
    std::back_inserter(newStr), 
    [] (char c) { 
     // I can get the index of iteration. 
     return (index % 5 == 0); 
    } 
); 
+1

간단한 for 반복문에 어떤 문제가 있습니까? –

+0

'copy_if'에서 같은 것을 할 수 있는지 알고 싶습니다. 귀하의 의견에 감사드립니다. :) – Husky

답변

1

당신은 문자열의 시작과 람다 함수의 캡처와 현재 반복기 따라 사용할 전달할 수 있습니다 (람다는 변경 가능합니다) :

std::string str("1000020000300004000050000"); 
std::string newStr; 

std::copy_if(str.begin(), str.end(), 
std::back_inserter(newStr), 
[it = str.begin(), beg = str.begin()] (auto c) mutable { 
    // I can get the index of iteration. 
    return (std::distance(it++, beg) % 5 == 0); 
} 

DEMO

+1

이것은 흥미로운 방법입니다. 비 RandomAccessIterator의 경우,'std :: distance'는 선형 복잡성을 가지고 있음을 주목하십시오 (이 특별한 경우에는 문제가되지 않습니다). 또한 일반적인 람다에는 C++ 14가 필요합니다. –

0

당신은 지역 변수의 인덱스를 추적 할 수 있습니다. 참고로 i을 캡처해야합니다. 즉 [&i]

int i = 0; 
std::copy_if(str.begin(), str.end(), 
    std::back_inserter(newStr), 
    [&i] (char c) { 
     int index = i++; 
     return (index % 5 == 0); 
    } 
); 
관련 문제