Removal Of Elements in a Vector Conatings User-Defined Object Basedon Value Contained in Object

  • Thread starter Adam Hartshorne
  • Start date
A

Adam Hartshorne

Hi All,

I have a vector of MyObject's user defined objects(with each containing
a bool type variable called myFlag). I want to go through the whole
vector and delete from it all the MyObjects's that have their myFlag set
to false. I can't work out a simple way of doing this, any suggests
would be much appreciated,

Adam
 
V

Victor Bazarov

Adam Hartshorne said:
I have a vector of MyObject's user defined objects(with each containing a
bool type variable called myFlag). I want to go through the whole vector
and delete from it all the MyObjects's that have their myFlag set to
false. I can't work out a simple way of doing this, any suggests would be
much appreciated,

Create a custom functor

class MyFlagTester {
bool desired;
public:
MyFlagTester(bool d) : desired(d) {}
bool operator()(MyObject const& o) const
{ return o.myFlag == desired; }
};

Then use it:

myVector.erase(std::remove_if(myVector.begin(), myVector.end(),
MyFlagTester(false)));

V
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,537
Members
45,022
Latest member
MaybelleMa

Latest Threads

Top