Re: Copy Constructors and Assignment Operator, When should I use?
On Mar 3, 9:54 pm, rockdale <rockdale.gr...@gmail.com> wrote:
Erasing an element from a vector invalidates the all iterators after
the erased element, so the above is incorrect.
I read about this.
But when I call this function :
void removeFstItem(){
std::vector<ItemB>::iterat=
or vecItr;
for(vecItr = m_vecB.begi=
n();
vecItr !=
= m_vecB.end();
++vecItr){=
=
if(vecItr->bInt == 1){
=
m_vecB.erase(vecItr);
=
return;
=
}
}
}
I still can write out the rest elements (in this case, they should be
all invalidate), is it because I erase one element and then returned?
any explanation on this?
Yes, it would work okay if you just remove one element because you are
not using the iterator 'vecItr' after that erased element. You can, of
course, fetch the iterator to N'th element again and use it. It is
only the variables that hold the iterators before the erase that get
affected. I hope I could clearly convey.
One way to do it would
be:
std::vector<ItemB>::iterator itend =
std::remove_if(m_vecB.begin(), m_vecB.end(),
=
<condition that checks if
remove needed>
);
m_vecB.erase(itend, m_vecB.end());
<condition that checks if remove needed> is a function or a function
object. That would be coded as:
bool needRemove(const ItemB& item)
{
//check if item eligible for remove
//if yes, return true
//otherwise, return false
}
I tried the remove_if and googled remove_if
2 problems:
1. I got compiled error : remove_if is not a member of "std"
2. what should I passed into the needRemove function?
std::vector<ItemB>::iterator itend =std::remove_if(m_vecB.begin(),
m_vecB.end(), needRemove(???));
You don't need to pass anything. needRemove is a function that takes a
single argument (unary). remove_if is codes as it will call needRemove
for all elements in the range provided. Those individual elements are
what are used to make the call to needRemove and that happens inside
remove_if. You just need to pass the function pointer to the
algorithm. To use remove_if, you should include <algorithm>.