2017-09-24 5 views
0

나는 다음과 같은 기능이 있습니다기능 현재 위치에서

shared_ptr_of_points filter(const shared_ptr_of_points input){ 
    shared_ptr_of_points result = make_new(); 
    for(const auto item:input->points){ 
     if(cond(item)){ 
      result->add_point(item); 
     } 
    } 
    return result; 
} 

일반적인 사용은 다음과 같습니다 그러나

auto filtered_points = filter(some_noisy_points); 

, 그것은 또 다른 방법으로 사용할 수 있습니다 :

some_points = filter(some_points); 

위의 구현은이 경우 제대로 작동합니다. 그러나 불필요한 복사가 수행됩니다.

질문 :이 문제의 일반적인 해결책은 무엇입니까?

P. 두 경우 모두 잘 작동하려면 첫 번째 복사본에서 복사가 수행되어야합니다 (인수를 const으로 받아 들여야 함). 두 번째 경우에는 복사가 발생하지 않아야합니다.

과부하는 정상이지만 두 개의 분리 된 기능을 만드는 것은 옵션이 아닙니다.

당신은 약간 다른 프로토 타입을 사용하여 목표를 잘 달성 할 수
+1

더 실버 없다 여기서 총알은 내부에서 작동하는 별도의 함수를 만든다. (아마도'std :: remove_if'가 될 것이고 그다지 그렇지 않다). –

+1

* "오버로드가 정상이지만 두 개의 분리 된 함수를 만드는 것은 옵션이 아닙니다."* - 그냥 궁금해서 선택의 여지가없는 이유는 무엇입니까? – WhiZTiM

+1

함수의 "적절한"버전을 구현하십시오. 이제'const' 매개 변수를 취하는 버전을 작성하십시오. 첫 번째 매개 변수의 복사본을 만든 다음 "적절한 위치"버전을 호출하여 작동합니다. 그것은 "이 문제에 대한 고전적인 해결책"입니다. –

답변

2

: 당신이 그것을 사용하고자하는 경우

void filter(const shared_ptr_of_points & input, shared_ptr_of_points & output) 

후 가능한 구현은 다음과 같이 표시됩니다

// Example program 
#include <iostream> 
#include <string> 
#include <memory> 
#include <vector> 
#include <algorithm> 

typedef std::shared_ptr<std::vector<int>> shared_ptr_of_points; 

bool cond(int x){ 
    return x > 100; 
} 

void filterCopy(const shared_ptr_of_points & input, shared_ptr_of_points & output){ 
    if (!output){ 
     output = std::make_shared<std::vector<int>>(); 
    } 

    for(const auto item:*input){ 
     if(cond(item)){ 
      output->push_back(item); 
     } 
    } 
} 

void filterInplace(shared_ptr_of_points & inout){ 
    inout->erase(std::remove_if(inout->begin(), inout->end(), [](int x){return !cond(x);}), inout->end()); 
} 

void filter(const shared_ptr_of_points & input, shared_ptr_of_points & output){ 
    if (output == input) 
     filterInplace(output); 
    else 
     filterCopy(input, output); 
} 

int main() 
{ 
    shared_ptr_of_points pts = std::make_shared<std::vector<int>>(); 
    pts->emplace_back(100); 
    pts->emplace_back(200); 
    pts->emplace_back(300); 

    for(const auto item:*pts){ 
     std::cout << item << std::endl; 
    } 

    std::cout << "**********" << std::endl; 

    shared_ptr_of_points resCopy; 
    filter(pts, resCopy); 
    for(const auto item:*resCopy){ 
     std::cout << item << std::endl; 
    } 

    std::cout << "**********" << std::endl; 

    filter(pts, pts); 
    for(const auto item:*pts){ 
     std::cout << item << std::endl; 
    } 
} 
관련 문제