Delete the STD: Map element in the C ++ traversal.

Source: Internet
Author: User

It is very easy to delete an element in STD: List. Use the erase method directly,CodeAs follows:

 For  ( ITER    =    List. Begin  ( )  ;    ITER    !  =    List. End  (  ) ;  )     { 
If   ( Shoulddelete ( * ITER) )
ITER   =   List. Erase ( ITER ) ;
Else
++ ITER ;
}

Or simpler.

List. Erase  ( STD::  Remove_if  ( List. Begin  (  ) , List. End  ( ) , Shoulddelete ) , List_end (  )  )  ; 

However, according to the definition of void erase (iterator POS) in stl std: map, this erase does not return the iterator of the next element. Therefore, the STD: list method cannot be used.

The truth is that 'erase' in Associative containers doesn' t invalidate any iterators should t those that point to elements being erased (That's also true for 'sid: list '). for this reason, you don't really need 'map: erase 'to return an iterator. just do this

 For  ( ITER    =    Map.Begin  (  )  ;    ITER    !  =    Map. End (  )  ;  )     { 
If   ( Shoulddelete( * ITER ) )
Map. Erase ( ITER ++ ) ;
Else
++ ITER ;
}

Of course, this method is also suitable for STD: List and so on.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.