2

I have an STL list of pointers, along with another pointer of the same type. I need to perform a ton of operations on each of them. My current method is to push the pointer onto the list, iterate through everything, then pop the pointer back off. This works fine, but it got me wondering if there were a more elegant/less hacky way to iterate through a combination of things. (say if I had a pile of other additional things to add to the iteration)

The current functional, but a bit hacky way:

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

2 回答 2

3

The more idiomatic approach might be to encapsulate your "long list of operations" into a function, then call it as needed. For example:

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

Then, if you later need to apply foo to other items, just call as needed.

While there's nothing inherently evil about adding otherObject to myList in the manner you describe, it is in a way abusing the list and should probably be avoided if possible.

于 2012-06-18T02:48:08.687 回答
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 );
}
于 2012-06-18T02:53:01.403 回答