2012-06-18 104 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); 
}