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);
The more idiomatic approach might be to encapsulate your “long list of operations” into a function, then call it as needed. For example:
Then, if you later need to apply
footo other items, just call as needed.While there’s nothing inherently evil about adding
otherObjecttomyListin the manner you describe, it is in a way abusing the list and should probably be avoided if possible.