Detailed resolution of the erase usage and return values for the STL container set map vector
- 2020-04-02 01:39:09
- OfStack
Summarize my experience and lessons in work.
When using a list, set, or map to iterate over removing certain elements:
Use method 1 correctly
std::list< int> List;
std::list< int>::iterator itList;
for( itList = List.begin(); itList != List.end(); )
{
if( WillDelete( *itList) )
{
itList = List.erase( itList);
}
else
itList++;
}
Use method 2 correctly
std::list< int> List;
std::list< int>::iterator itList;
for( itList = List.begin(); itList != List.end(); )
{
if( WillDelete( *itList) )
{
List.erase(itList++);
}
else
itList++;
}
Use method 3 correctly
std::list< int> List;
std::list< int>::iterator it, next;
for( it = List.begin(), next = it, next ++; it != List.end(); it = next, ++next)
{
if( WillDelete( *it) )
{
List.erase(it);
}
}
Note: method 3 is more subtle, but note that method 3 is to determine whether the container is empty or not before using it, otherwise the iterator will fail.
I tested that set.erase does not return the iterator and list returns.
The vector
Delete operation
std::vector <PACK_PRINT>::iterator It ;
for(It=printItems.begin();It!=printItems.end();)
{
//I mean, how do you know that pack_print.bh =0 in printItems
if( It.bh ==0) //Is that right?
{//delete
It=printItems.erase(It);
}
else
{// Don't delete
++It;
}
}
std::vector <PACK_PRINT> printItems;
int i = 0;
while(i < printItems.size())
{
if(printItems[i].bh == 0) //So let's say I want to delete pack_print.bh =0 in the printItems. Is there anything wrong with deleting this way?
{//delete
printItems.erase(printItems.begin() + i);
}
else
{// Don't delete
++i;
}
}