C + + container overview and Sequence container basic operations __c++

Source: Internet
Author: User
Tags data structures

A container is a collection of certain types of objects, and the container class is divided into sequential containers and associative containers. Container Basic Operation

Some basic operations of the container class are as follows:

Defining and initializing

Each container defines a default constructor. In addition to array, the default constructor for the other container creates an empty container of the specified type, and both can accept parameters for the specified container size and element initial value.


initializing a container to a copy of another container there are two ways to create a new container as a copy of another container: You can copy the entire container directly, or copy by an iterator to the specified element range. The latter does not apply to array.
When you create a copy of a container as a second container in the first way, the type of the two container and its element type must match. In the second way--by passing the iterator parameter, the container type is not required to copy. Also, the element types in the new container and the original container can be different, as long as the element to be copied is converted to the element type of the container to initialize (for example, the const char* element can be converted to a string).
Sequential Container

The

         sequential container provides programmers with the ability to control element storage and sequential access. This order is not dependent on the value of the element, but corresponds to the position of the element when it is added to the container. The sequence container for the
        c++ has several vectors, deque, lists, Forward_list, array, and string. They all provide a quick sequential access to the element's operations. But they differ in the order of access, the cost of adding/removing elements.
        string and vectors are variable container classes that are designed to hold characters, both of which hold the elements in contiguous memory space. Because the elements are continuously stored, it is very fast to compute the address by the element subscript. However, adding/removing elements in the middle of both containers can be time-consuming: after an insert/delete operation, all elements after insertion/deletion need to be moved to maintain continuous storage. Also, adding an element may sometimes require allocating additional storage space, in which case each element must be moved to a new storage space. The
        list and forward_list Two containers support Quick Insert/delete operations at any location in the container, and list is a two-way list, Forward_ List is a one-way list. As a cost, the two containers do not support random access to elements and can only be accessed sequentially. Furthermore, the additional memory overhead of these two containers is greater than vectors and deque and array. The
        deque is a two-terminal queue that supports fast random access, but adds/deletes elements at locations other than the end of the tail. However, adding/removing elements at both ends of the deque is comparable to the speed of the list or forward_list.

The

        array is a container class closest to the original array, and its object size is fixed. Therefore, array does not support actions that add and remove elements and change the size of the container. Array is a more secure and easy to use arrays type than a built-in array.

The characteristics of the

         serial container determine what kind of container we should use. In general, Vector is the best choice unless you have a good reason to choose another container. If your program requires random access to elements, you should not use list and forward_list. Use Deque if your program only needs to insert or delete elements at the beginning and the ends. In general, the dominant operation in the application determines the choice of the container type. The
related action assignment and Swap assignment operator replaces all elements in its left container with copies of elements in the right container:
C1 = c2;
C1 = {A, b, c};
         the left container will be equal to the right container after the first assignment operation. If the original size of two containers is different, the size of both is the same as the original size of the right container after the assignment operation. After the second assignment, the size of the C1 becomes 3, the number of values in the curly braces list.
         is different from a built-in array, the standard library array type allows you to assign values. The Operation object on the left and right side of the assignment must have the same type. Also, because the array type size is fixed, the operator on both sides of the assignment number is required to be equal in size. In summary, all attempts to change the size of the original array type are not allowed. The
Use assign (Sequential container only)
         assignment operators require the same type for the left and right operations objects. It copies all the elements in the right-hand operation object to the left Operation object. The sequential container (except array) defines a assign member function that allows us to assign a value from a different but compatible type, or to assign a value from a subsequence of a container. The Assign action replaces all elements in the left container with the copy of the element specified by the parameter.
list<string> names;
Vector<const char*> Oldstyle;
Names.assign (Oldstyle.cbegin (), Oldstyle.cend ());

         The above code replaces the elements in names with a copy of the elements in the range specified by the iterator. The Assign parameter determines how many elements are in the container and what the value is. This operation cannot be done with an assignment operator because the two containers are of different types.

The


use swap         swap operation to exchange the contents of two containers of the same type. When swap is invoked, the elements in the two containers are exchanged. Also, swapping two of containers with swap is fast because the elements themselves are not swapped, and swap only swaps the internal data structures of the two containers. Also, swap does not copy, delete, or insert an element, so it is guaranteed to be done in constant time. The fact that the
         element will not be moved means that, except for string, the iterator, references, and pointers to the container are not invalidated after swap. They still point to the element that was pointed before the swap operation. However, these elements are already part of a different container after the swap operation. The
        swap operation has two exceptions, one is a string, and calling swap on string causes the iterator, reference, and pointer to fail. The other is array, and invoking the swap on array will actually exchange their elements. Therefore, the position of the element to which the pointer, reference, and iterator is bound is unchanged after the Array,swap operation, but the element value is already swapped with the value of the corresponding element in the other array.
         The above description of the swap operation is only for non-member version of Swap, that is, the Std::swap
container size operation          out Forward_list does not support size, each container type has three sizes-related operations. These three member functions are: size, empty, and max_size
sequence container actions add element

As you can see from the following table, although some containers do not support push_front operations, they do not have a similar restriction on insert operations (insert start position). So we can use insert to insert the element into the beginning of the container without worrying about whether the container supports Push_front. It should be noted, though, that it is legal to insert elements anywhere in vectors, deque, and strings. However, this can be time-consuming.


Delete Element

Accessing elements

Special Forward_list Action the successor of the element that was deleted or added before the element is added or deleted will change. To add or remove an element, we need to visit its predecessors in order to change the links of the precursors. However, Forward_list is a one-way linked list. In a one-way list, there is no simple way to get the precursor of an element. For this reason, the action to add or remove elements in a forward_list is done by changing the elements after the given element. In this way, we always have access to the elements that are affected by the add or remove operations.

Because these operations differ from the implementations of operations on other containers, Forward_list does not define inserts, Emplace, and erase, but rather defines operations named Insert_after, Emplace_after, and Erase_after.


change the size of the container

We can use resize to enlarge or shrink the container. If the current size is larger than the required size, the elements at the back of the container are deleted, and if the current size is less than the required size, the new element is added to the back of the container.


the container operation may invalidate the iterator

Adding elements to a container and deleting elements in a viewer may invalidate pointers, references, or iterators that point to container elements. A failed pointer, reference, or iterator will no longer represent any elements.


         After adding elements to the container:
• If the container is a vector or string and the storage space is reassigned, point to the container's iterator, Both the pointer and the reference are invalidated. If the storage space is not reassigned, the iterator, pointer, and reference to the element before the insertion position are still valid, but the iterator, pointer, and reference to the element after the insertion point will be invalidated.
• For deque, inserting into any location other than the beginning and end causes the iterator, pointer, and reference to be invalidated. If you add an element at the beginning and end, the iterator fails, but the reference and pointer to the existing element does not expire.
• For lists and forward_list, the iterator that points to the container (including the end-after iterator and the first-forward iterator), pointers, and references is still valid.
         After removing elements from the container:
• An iterator, pointer, and reference that points to the deleted element in all containers will fail.
• For lists and forward_list, iterators that point to other locations in the container, including end-post iterators and first-forward iterators, references, and pointers, are still valid.
• For deque, if you delete an element anywhere other than the beginning and end, the iterator, reference, or pointer to other elements outside the deleted element will also fail. If you delete the tail element of the deque, the trailing iterator will also fail, but other iterators, references, and pointers are unaffected, and if you delete the first element, these will not be affected.
• For vectors and strings, the iterators, references, and pointers to elements that precede the deleted element are still valid.
         Because code that adds elements to the iterator and deletes elements from the iterator may invalidate the iterator, Therefore, it is important to ensure that the iterator is repositioned correctly after each change of the container's operation. In addition, minimizing the need for an iterator to maintain a valid program fragment is also a good way to manage iterators. The new standard that the


        c++11 starts is much faster than the old version because the new standard library supports the movement of objects, whereas the old standard library can only copy objects. \ cubby Therefore, the performance of the new standard storage capacity compared to the old standard library has a relatively large increase.

This digest is from "C + + Primer (Chinese version) Fifth Edition"


Related Article

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.