Add, delete, modify, and delete a list in STL

Source: Internet
Author: User

The list in STL is an efficient list that can be quickly inserted or deleted. You can put any data type, including pointers.
In use, it is best to separate declaration from adding data to it, that is, first declaration and then use. This is also the basic programming habit.
Example: STL: List <int> myintlist;
This is a list of int-type values that can be stored. Currently, the list is empty.
If you want to add data to it, you can use either of the following four methods:
Myintlist. Assign (3, 2 );
Myintlist. push_back (2 );
Myintlist. push_front (2 );
Myintlist. insert (myintlist. Begin (), 2 );
Generally, push_back and push_front are most commonly used, that is, pushing data to the end and start of the list. Assign is generally used to put all the data of a set into the list at a time, while insert is mainly used to insert one or more elements at a specified position, with multiple overload functions.
 
If you want to delete an element, the content in the list is of the basic type (resources do not need to be released separately), you can directly use the erase function. Otherwise, you must use the iterator, retrieve the reference of each element before deleting it. For example:
STL: List <myobject *> mylist; // contains references to custom objects.
STL: List <myobject *>: iterator itr; // iterator
For (itr = mylist. Begin (); itr! = Mylist. End (); ++ itr)
{
Delete * itr; // delete an element
}
 
Mylist. Clear (); // clear the list
 
Note that the remove method should be used with caution. Remove only removes the qualified elements from the list. If the element is a reference, the reference is not safely deleted.
 
Of course, the list also provides multiple other functions that can sort, merge, exchange, and flip the list, combined with the basic list method, we can use list to do more.
 
 

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.