C ++ remove_if for object vector

I have a vector (order is important) of objects (allows myobj class to call them), where I try to delete several objects at once.

class vectorList { vector<*myobj> myList; }; class myobj { char* myName; int index; bool m_bMarkedDelete; } 

I thought the best way to do this is to mark specific myobj objects for deletion, and then call myList.remove_if () on the vector. However, I'm not quite sure how to use predicates and the like. Should I create a member variable in an object that allows me to say that I want to remove myobj, and then create a predicate that checks if a member variable has been set?

How to implement a predicate as part of the vectorList class?

+24
c ++ vector stl predicate
Oct. 31 '11 at 18:49
source share
2 answers

Should I create a member variable in an object that allows me to say that I want to remove myobj, and then create a predicate that checks if a member variable has been set?

Have you not done this already? Isn't that what m_bMarkedDelete ? You should write a predicate as follows:

 bool IsMarkedToDelete(const myobj & o) { return o.m_bMarkedDelete; } 

Then:

 myList.erase( std::remove_if(myList.begin(), myList.end(), IsMarkedToDelete), myList.end()); 

Or using lambdas:

 myList.erase( std::remove_if(myList.begin(), myList.end(), [](const myobj & o) { return o.m_bMarkedDelete; }), myList.end()); 

If your class does not actually have this member, and you ask us if that is the case, then I would say no. What criteria did you use to decide whether to mark it for deletion? Use the same criteria in your predicate, for example:

 bool IndexGreaterThanTen(const myobj & o) { return o.index > 10; } 

note - The functions that I wrote are, of course, not valid, since all your members are private. So you need access to them.

+31
Oct 31 '11 at 19:08
source share

A predicate is basically a conditional comparison. It can be a function or an object. Here is an example of using the new C ++ lambdas. This code will go through the vector and delete values โ€‹โ€‹equal to 3.

 int arg[6] = {1, 2, 3, 3, 3, 5}; std::vector<int> vec(arg, arg+6); vec.erase( std::remove_if( vec.begin(), vec.end(), [](int i){ return i == 3;}), vec.end()); 

Edit:. For pointers, you can say that you have a vector or interfaces that you could set to nullptr , and then delete them in a package with almost the same code. In VS2008 you will not have lambdas, so instead of comparing predicate function or structure.

 bool ShouldDelete(IAbstractBase* i) { return i == nullptr; // you can put whatever you want here like: // return i->m_bMarkedDelete; } std::vector<IAbstractBase*> vec; vec.erase( std::remove_if( vec.begin(), vec.end(), ShouldDelete), vec.end()); 
+8
Oct 31 '11 at 19:03
source share



All Articles