C + + Learning Order container (i)

Source: Internet
Author: User

A container is a collection of certain types of objects. Sequential containers (sequential container) provide us with the ability to control the order in which elements are stored and accessed. This order does not depend on the value of the element, but rather corresponds to the position of the element when it is added to the container.

Overview of sequential container types
Container name Container Properties Access attributes modifying attributes
Vector Variable size array Random Fast trailing insert/delete speed
Deque Dual-ended queues Random High insertion/deletion speed at the beginning and tail
List Doubly linked list Bidirectional order Insertion/deletion is fast in any position
Forward_list Single Necklace table One-way order Insertion/deletion is fast in any position
Array Fixed size array Random Cannot add/remove elements
String Similar to vectors, but only characters are saved Random Fast trailing insert/delete speed

In addition to fixed-size arrays, other containers provide efficient, flexible memory management. In some cases, a storage policy can affect whether a particular container supports specific actions:

1.string and vectors keep elements in contiguous memory space, so it is very fast to calculate the address from off-duty, but it is time consuming to add/remove elements in the middle of the container, all elements after the position must be inserted/removed (to ensure continuous storage); Adding an element may sometimes require allocating additional storage space, at which point each element must be moved to a new storage space.

2.list and Forward_list are designed to make it fast to add/delete operations anywhere in the container, but at the cost of accessing an element, the entire container must be traversed, and the additional memory overhead of the two containers is significant compared to vectors, deque, and arrays.

3.deque Add/Remove elements at intermediate cost (possibly) very high, but at both ends Add/remove soon

The detailed structure of the sequential containers also need to look at the "STL Source resolution" Related books ...

Container Library Overview Iterator begin and End members

The Begin and end operations generate iterators that point to the position of the first element and the trailing element in a container

Auto it1 = A.begin ();        List<string>::iteratorauto it2 = A.cbegin ();      //list<string>:: const_iterator//explicitly specifies type list<string>::iterator it3 = a.begin (); list<string >::const_iterator IT4 = a.begin ();//reverse iterator is not in the scope of this discussion  

Container definition and initialization Initializes a container to a copy of another container

I. Copy the entire container directly: requires that the type of the two containers is extremely element type must match

II. Copy an iterator to a specific element range (except for array): The container type is not required, the element type can be converted to the target element

List initialization
List<string> authors = {"Alan", "Bob", "David"};vector<const char*> articles = {"A", "an", "the"};lis T<string> List2 (authors); Correct: type matching deque<string> authlist (authors); Error: Container type mismatch vector<string> words (articles); Error: Container type mismatch//correct: const char* element can be converted to stringforward_list<string> words (Articles.begin (), Articles.end ());

Constructors related to the order container size

The sequential container (except array) provides a constructor that accepts a container size and an (optional) element initial value

Vector<int> Ivec (Ten,-1);            10 int elements, each initialized to -1listing<string> Svec (x, "HI");     10 string, each initialized to "HI" forward_list<int> ivec (x);         10 elements, each initialized to 0deque<string> Svec (x);            10 elements, each of which is a null string

Standard library array has a fixed size

To define an array, specify the element type and container size

Array<int>::size_type J;        Error:array<int> is not a type array<int, 42> ia1;        Initialize int by default

Note: Although we cannot copy or assign an object to a built-in array type, array does not have this limitation, but the assigned array has the same element type and size as the original array

Assignment and Swap assignment operator assignment values

I. require that the left and right operands have the same type

II. If the original size of the two containers is different, the value of the assignment is the same size as the container on the right.

Assign Assignment value

I. This action does not apply to associative containers and array

II. Allow assignment from a different but compatible type, or assign a value from a sub-sequence of a container

III. Because the assign operation first deletes all the previously stored elements in the container, the iterator passed to the Assign function cannot point to the element within the container that called the function

Using swap

I. In addition to array, the operation of exchanging two container contents is guaranteed to be very fast, because the element itself is not exchanged, swap only exchanges the internal structure of two containers.

Ii. in addition to string, iterators, references, and pointers to the container do not expire after the swap operation, because the data structure of the interchange does not change the value stored by the elements, and the element's owning container has changed, so the address of the element stored in the container has changed.

For example: In GCC, the swap of a vector is an exchange of three pointers: _m_start,_m_finish,_m_end_of_storage, and the reference is not untied.

Iii.swap two arrays will actually exchange their elements (corresponding, the swap time and the size of the array are positively correlated): After swapping, two arrays exchanged the values of the elements, but the stored addresses in the container did not swap; In addition, after the swap operation, the pointer, The elements bound by the reference and iterator remain unchanged, but the values within the element have changed

Iiii.swap A string causes pointers, references, and iterators to fail, an explanation is found: https://www.zhihu.com/question/57561910

Sequential container operations
Sequential container operations Operation function Support Container return value
Push_back Append element at end of container List,vector,deque,string void
Push_front Inserting elements into the container head List,forward_list,deque void
Insert Add elements or insert in-range elements before container-specific locations Vector,deque,list,string Returns an iterator that points to the first newly added element
Emplace_front construct element, insert element to container Head List,forward_list,deque void
Emplace Construct elements, add elements before container-specific locations, or insert in-range elements Vector,deque,list,string Returns an iterator that points to the first newly added element
Emplace_back construct element, append element at container tail List,vector,deque,string void
Pop_front Delete First element List,forward_list,deque void
Pop_back Delete Tail element List,vector,deque,string void
Erase To delete an element from a container-specific location or to delete an in-scope element Vector,deque,list,string Returns an iterator pointing to the position after the last element deleted

List<string> slist;//is equivalent to calling Slit.push_back ("HI"); Slist.insert (Slist.begin (), "HI"); vector<string > Svec = {"A", "B", "C"};//a pair of iterators, cannot point to the inserted container Slist.insert (Slist.begin (), Svec.end ()-2, Svec.end ());// Delete multiple elements slist.clear ();                                        Delete all elements in the container slist.erase (Slist.begin (), Slist.end ());      Equivalent call   

Special Forward_list operation
Actions to insert or delete elements in Forward_list
Lst.before_begin ()

Returns an iterator to an element that does not exist before the first element of the list, and this iterator cannot be dereferenced. Cbefore_begin () returns a const_iterator

Lst.cbefore_begin ()
Lst.insert_after (p,t)

Inserts an element at the position after the iterator p. T is an object, n is the number, B and e are a pair of iterators representing the range (B and E cannot point to the LST), and IL is a list of curly braces.

Returns a pointer to the last iterator that inserts an L element.

If the range is empty, then P is returned, and if P is the trailing iterator, the function behavior is undefined.

Lst.insert_after (p,n,t)
Lst.insert_after (P,b,e)
Lst.insert_after (P,il)
Emplace_after (P,args) Creates an element after the position specified by P using args, and returns an iterator to the new element. If P is an after-tail iterator, the function's behavior is undefined
Lst.erase_after (P)

Deletes the element after P points to, or removes the element from B until (but not including) E.

Returns an iterator that points to the element after the element being deleted, and returns a trailing iterator if no such element exists, and if p points to the tail element of the LST or is a trailing iterator, the function's behavior is undefined

Lst.erase_after (P,e)

Container operation may invalidate the iterator

After adding an element to the container:

1. If the container is vector or string, and the storage space is reassigned, the iterator, pointer, and reference to the container are invalidated, and if the storage space is not reassigned, the iterator, pointer, and reference that precedes the insertion element are valid, pointing to the iterator to the element after the insertion element, Both the pointer and the reference are invalidated.

2. For deque, inserting to any position except the end-to-end position causes iterators, references, and pointers to fail, and if the element is added at the end-to-end position, the iterator will fail, but the reference and pointer to the element that exists will not be invalidated.

3. For list and forward_list, the iterator that points to the container (including the tail-end iterator and the first-front iterator), pointers, and references are valid.

Container after deleting elements:

1. For list and forward_list, the iterator that points to the container (including the trailing and first-front iterators), pointers, and references are valid

2. For Deque, an iterator, reference, and pointer that points to other elements outside the element are invalidated if the element is deleted anywhere outside the end of the path. If the tail element of the deque is deleted, the trailing iterator fails, but the other iterators, references, and pointers are not affected; If you delete the first element, these will not be affected.

3. For vector and string, the iterator, reference, and pointer to the element before the element is deleted is valid

When we delete an element, the trailing iterator is always invalidated.

Therefore, you must ensure that you reposition the iterator correctly after each change to the container, and that you do not save the end-return iterator.

Reference:

http://blog.csdn.net/jy_95/article/details/47679185

http://blog.csdn.net/imkelt/article/details/52213735


C + + Learning Order container (i)

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.