2012-06-18 2 views
2

동일한 유형의 다른 포인터와 함께 포인터의 STL 목록이 있습니다. 나는 그들 각각에 대해 1 톤의 작업을 수행해야한다. 내 현재 방법은 목록에 포인터를 밀어 모든 것을 반복하고, 포인터를 다시 튕겨내는 것입니다. 이것은 잘 작동하지만 사물의 조합을 반복 할 수있는보다 우아하고 덜 해킹 된 방법이 있는지 궁금하게 생각합니다. 현재의 기능을목록 및 개별 개체에 대한 C++ 반복

(나는 반복에 추가 할 다른 부가적인 것들의 더미가 있다면 말),하지만 조금 해키 방법 :

std::list<myStruct*> myList; 
myStruct* otherObject; 

//the list is populated and the object assigned 

myList.push_back(otherObject); 
for(std::list<myStruct*>::iterator iter = myList.begin(); iter != myList.end(); ++iter){ 

     //Long list of operations 

} 

myList.pop_back(otherObject); 

답변

3

더 관용적 접근 방식은 당신의 "긴 목록을 캡슐화 할 수 있습니다 작업 "을 함수로 변환 한 다음 필요에 따라 호출하십시오. 예를 들어 : 나중에, 다른 항목에 foo을 적용해야하는 경우 필요에 따라

void foo (myStruct* x) 
{ 
    // Perform long list of operations on x. 
} 

... 

{ 
    std::list<myStruct*> myList; 
    myStruct* otherObject; 

    // The list is populated and the object assigned. 

    foo (otherObject); 
    for(std::list<myStruct*>::iterator iter = myList.begin(); iter != myList.end(); ++iter) 
    { 
     foo(*iter); 
    } 
} 

그런 다음, 단지 호출합니다.

당신이 설명하는 방식으로 myListotherObject를 추가하는 방법에 대한 본질적으로 악한 것도 없지만,이 목록을 학대하는 방식이며, 가능하면 아마 피해야한다.

+0

지금은 정말 바보 같아요, 하하. 고맙습니다! – akroy

+0

@Akroy : 아무 걱정도 없습니다. 기꺼이 도와 드리겠습니다. BTW : 우리 모두는 그 순간을 가지고 있습니다 ... – Mac

+0

여기에는 for_each라고하는 에 정의 된 알고리즘이 있습니다. 여기에 대한 자세한 내용은 http://www.cplusplus.com/reference/algorithm/for_each/ – zxcdw

1
void doStuff(myStruct& object) 
{ 
    //Long list of operations 
} 

int main() 
{ 
    std::list<myStruct*> myList; 
    myStruct* otherObject; 

    //the list is populated and the object assigned 

    for(auto iter = myList.begin(); iter != myList.end(); ++iter) 
    { 
     doStuff(**iter); 
    } 
    doStuff(*otherObject); 
}