2012-06-18 71 views
2

我有一個STL指針列表,以及另一個相同類型的指針。我需要對他們每個人進行大量的操作。我目前的方法是將指針推到列表上,遍歷所有內容,然後彈出指針。這工作正常,但它讓我想知道是否有一種更優雅/不太古怪的方式來迭代事物的組合。 (說,如果我有其他附加的東西一堆添加到迭代)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

更慣用的方法可能是封裝的「長名單操作「轉換爲函數,然後根據需要調用它。例如:

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); 
    } 
} 

然後,如果以後需要申請foo到其他項目,只需根據需要調用。

雖然在描述的方式中添加otherObjectmyList本身並不是什麼壞事,但它在某種程度上濫用了列表,應儘可能地避免。

+0

我現在覺得真的非常愚蠢,哈哈。謝謝! – akroy

+0

@Akroy:不用擔心,樂意幫忙。順便說一句:我們都有這些時刻...... – 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); 
}