2012-09-06 10 views
0

사용자 정의 클래스에 대한 포인터 목록을 몇 개 있습니다 (클래스는 기본 데이터가있는 간단한 Person입니다). 모든 목록에서 새 목록 하나만 포틀랜드 (도시 == 포틀랜드)에서 온 사람 만 포인터 (얕은 사본)를 복사 하시겠습니까? STL (목록)의 목록을 사용하고 있습니다. 나는 C++ 11을 사용할 수 없다.일부 stl 목록을 하나의 속성으로 만 복사하는 방법

class Person{ 
public: 
long id; 
string name; 
string last_name; 
string city 

}; 

답변

2

C++ 11에서는 copy_if 및 람다 사용해야합니다 : 당신이 (람다 또는 copy_if을 가지고 있지 않는) 이전 플랫폼이있는 경우

std::list<Person*> src, dst; 

std::copy_if(src.cbegin(), src.cend(), std::back_inserter(dst), 
      [](Person * p) -> bool { return p->city == "Portland"; }); 

, 당신은해야합니다을 루프를 수동으로 입력하십시오.

for (std::list<Person*>::const_iterator it = src.begin(), e = src.end(); it != e; ++it) 
{ 
    if ((*it)->city == "Portland") { dst.push_back(*it); } 
} 
+2

"나는 C++ (11)를 사용할 수 없습니다":( –

2

예 : C++ 03.

struct PersonComparerByCity : public std::unary_function<Person*, bool> 
{ 
    PersonComparerByCity(const std::string& c):city(c) { } 
    result_type operator() (argument_type arg) const 
    { return arg && arg->city == city; } 
private: 
    std::string city; 
}; 

std::list<Person*> p; 
std::list<Person*> result; 
std::remove_copy_if(p.begin(), p.end(), std::back_inserter(result), 
std::not1(PersonComparerByCity("Portland"))); 

http://liveworkspace.org/code/a8e36e63b1f9924281768d90f7a090da

관련 문제