Chapter 9-Chapter 10 containers and Algorithms

Source: Internet
Author: User

Chapter 9 ordered container vector list deque

1. to define a special container, you must add a pair of angle brackets after the container name. The angle brackets provide the type of elements stored in the container: vector <string> SVEC; // empty vector that can hold strings

All container types define the default constructor to create empty container objects of the specified type. The default constructor does not contain parameters. In addition to the default constructor, the container type also provides other constructor functions so that programmers can specify the initial values of elements,

C <t> C; // create an empty container named C. C is the container type name, such as vector, T is the element type, such as Int or string. Suitable for all containers

C (C2); // container C2 and C must have the same container type and store elements of the same type.

C (B, E); // create C, whose elements are copies of the elements within the range of iterator B and specimen E.

C (n, T); // create container C with n elements whose values are T. The value T must be the element type value of container type C, or it can be converted to this type of value. C (n); // create a container C with N initialization elements. When this type is used for initialization, the element type must be a built-in or composite type, or a class type that provides the default constructor
If the element type does not have a default constructor, the initialization type of the specified element must be displayed.

The constructor that accepts the container size as a parameter applies only to the ordered container, but the associated container does not support such initialization.

2. the type constraints of elements in the container must meet the following two constraints:

* The element type must support the value assignment operation.

* Element-type objects must be able to be copied

References do not support assignments of the general meaning, so there is no elemental reference type container. Io library types do not support copying or assigning values. Therefore, you cannot create a container to store IO objects.

The replication and assignment functions are the minimum requirements for the element type of the container. In addition, some operations have special requirements on element types. If the element type does not support these special requirements, the related container operations cannot be executed. We can define this type of containers, but some specific operations cannot be used.

Because the container is restricted by the element type of the container, the elements that can be defined are containers of the container type. Vector <vector <string> lines; two adjacent> symbols must be separated by spaces to show that they are separate symbols. Otherwise, the system considers> as a single symbol, is the right operator, and the result leads to a compilation error.

When writing a program using the iterator, you must note which operations will invalidate the iterator. Invalid iterators can cause serious runtime errors.

3. Operations of the sequential container * add an element to the container * delete an element in the container * set the container size * (if any) to obtain the first and last elements in the container.

Container-defined type alias

Size_type unsigned integer, enough to store the maximum possible container length of this container type

Iterator the iterator type of this container type

Read-Only iterator type of the const_iterator Element

Reverse_iterator iterator for backward addressing elements

Read-only backward iterator of the const_reverse_iterator Element

Difference_type is enough to store signed integer values of the two iterators, which can be negative.

Value_type element type

The left Value Type of the reference element, which is a synonym for value_type &

The constant left Value Type of the const_reference element, which is equivalent to const value_type &

 

C. Begin () returns an iterator pointing to the first element of container C.

C. End () points to the next position of the last element of container C.

C. rbegin () It points to the last element of container C

C. rend () It points to the position before the first element of container C

 

4. add elements to the ordered container

C. push_back (t) adds an element whose value is t at the end of container C, and returns the void type.

C. push_front (t) adds an element whose value is t at the front end, and returns the void type.

Only applicable to list and depue container types

C. insert (P, T) inserts an element whose value is t before the element pointed to by P in the iterator, and returns the iterator pointing to the newly added element.

C. insert (p, N, T) returns the void type.

C. insert (p, B, E)

When an element is added to a container, the system copies the element value to the container. Similarly, when an element is used to initialize a new container, the new container stores a copy of the original element. The copied original values are irrelevant to the elements in the new container. After that, when the element values in the container are changed, the copied original values are not affected, and vice versa.

Any insert or push operations may invalidate the iterator. When writing a loop to insert elements to a vector or deque container, the program must ensure that the iterator is updated after each loop.

5. The comparison container must have the same container type and the element type must also be the same. Container comparison is based on the comparison of elements in the container.

Container size operation

C. Size () returns the number of elements in container C. The return type is C: size_type.

C. max_size () returns the maximum number of elements that can be accommodated in container C. The return type is the same as that in container C.

C. Empty ()

C. resize (n) adjusts the length of container C so that it can accommodate n elements, if n <C. size () is used to delete multiple elements. Otherwise, add new elements whose values are initialized.

C. Resize (n, T) adjusts the size of container C so that it can accommodate n elements. All newly added element values are t

The resize operation may invalidate the iterator. The resize operation on the vector or deque container may invalidate all its iterators. For all container types, if the resize operation compresses the container, the iterator pointing to the deleted element becomes invalid..

6. Access Elements

C. Back () returnsReference. If C is null, the operation is not defined.

C. Front () returns the first element of container CReference. If C is null, the operation is not defined.

C [N] returns the reference of an element whose subscript is N. If n <0 or N> = C. Size (), this operation is not defined,Applicable to vector and deque containers.

C. At (n) returns the reference of the element whose subscript is N. If the subscript is out of range, this operation is not defined,Only applicable to vector and deque containers.

7. Delete Elements

C. Erase (p) deletes the element of the iterator P value and returns an iterator pointing to the element after the deleted element. If P points to the last element in the container, the returned iterator points to the next position beyond the container's end. If P itself is an iterator pointing to the next position beyond the end, the function is not defined.

C. Erase (B, E)
Delete all elements in the range marked by iterators B and E, and return an iterator pointing to the elements behind the deleted element segment. If e itself is an iterator pointing to the next position beyond the end, the returned iterator also points to the next position beyond the end of the container

C. Clear () deletes all elements of container C. Return void

C. pop_back () deletes the last element of container C and returns void. If C is an empty container, the function is not defined.

C. pop_front () deletes the first element of container C. Return void. If C is an empty container, the function is not defined.

The erase, pop_front, and pop_back functions indicate that all iterators pointing to the deleted element are invalid. For a vector container, the iterator pointing to the elements after the deletion point usually fails. For a deque container, if the deletion does not contain the first or last element, all iterators related to the deque container will become invalid.

8. Assignment and swap

The assignment and assign operations invalidate all iterators of the left operand container. The swap operation does not invalidate the iterator. After the swap operation is completed, the iterator still points to the same element even though the exchanged elements are already stored in another container.

C1 = c2 delete all elements of container C1, and then compose the elements of C2 to C1. C1 and C2 must be of the same type (including the container type and element type)

C1.swap (C2) Exchange Content: after calling this function, C1 stores the original C2 elements, while C2 stores the original C1 elements. C1 and C2 must be of the same type. This function is usually executed faster than copying C2 elements to C1.

C. Assign (B, E) reset the elements of C: Copy all the elements in the range marked by iterator B and E to C. B and E must not be the iterator pointing to elements in C.

C. Assign (n, T) resets container C to store n elements whose values are T.

Like the constructor for copying container elements, if the two containers have the same element type, you can assign a value to one container using the value assignment operator =. If the element types are different but compatible with each other in different (or identical) types of containers, the assign function must be used for the value assignment operation. Because the assign operation first deletes all elements originally stored in the container, the iterator passed to the assign function cannot point to the elements in the container that calls the function.

9. Self-Growth of vector containers

The implementers of the standard library use the memory allocation policy to store elements continuously at the minimum cost. The convenience of access elements makes up for the storage cost.

Capacity and reserve members

The capacity operation gets the total number of elements that can be stored before the container needs to allocate more storage space. The reserve operation tells the vector container how many elements should be reserved.

Size indicates the number of elements currently owned by the container, while capacity indicates the total number of elements that the container can store before it has to allocate a new bucket.

Every time a vector container has to allocate a new bucket, it is re-allocated by doubling the current capacity allocation policy.

 

The push_front operation is not supported for both the vector container and the string type.

 

10. Container Adapter

Adapters are commonly used in the standard library, including container adapters, iterator adapters, and function adapters. Essentially, an adapter is a mechanism that makes the behavior of one thing look similar to the behavior of another thing. The container adapter allows an existing container type to work in a different abstract type.

The standard library provides three sequence container adapters: queue, priority_queue, and stack.

The default stack and queue are implemented based on the deque container, while the priority_queue is implemented on the vector container. When creating an adapter, You can overwrite the associated basic container type by specifying an ordered container as the second type real parameter of the adapter.

For a given adapter, the associated container must meet certain constraints. The basic container associated with the stack adapter can be any sort of sequential container type. The queue adapter requires that the associated basic container must provide push_front operation, so it can only be built on the list container, not on the vector container. The priority_queue adapter requires random access, so it can be built on a vector or deque container, but not on a list container.

Priority_queue does not directly place the new element at the end of the queue, but is placed before the element with a lower priority than it. By default, the standard library uses the <operator of the element type to determine the priority relationship between them.

 

Chapter 10 associated containers

The associated container stores and reads elements through keys, while the ordered container stores and accesses elements sequentially by the position of elements in the container. Map elements are organized in the form of key-value pairs: Keys are used as the index of elements in map, while values represent the stored and read data. Set only contains one key, and effectively supports queries on whether a key exists.

1. Reference: The pair type is defined in the utility header file.

Pair <T1, T2> P1; creates an empty pair object. Its two elements are T1 and T2, respectively, and are initialized with values.

Pair <T1, T2> P1 (V1, V2); at the same time, the first member is initialized to V1, and the second member is initialized to V2.

Make_pair (V1, V2) creates a pair object with V1 and V2 values. The element types are V1 and V2 respectively.

P1 <P2: when the number of pair objects between two pair objects is smaller than the calculation value, the definition follows the dictionary order: If p1.first <p2.first or! (P2.first <p1.first) & p1.second <p2.second, true is returned.

P1 = P2

P. First returns the (public) data member named first in P.

P. Second: returns the (public) data member named second in P.

2. The associated containers share most ------- but not all -------- ordered container operations. Associated containers do not provide front, push_front, pop_front, back, push_back, and pop_back operations.

The fact that "container elements are arranged in the order of keys" is an important conclusion: When iteratively traversing the associated containers, we can ensure that the elements are accessed in the order of keys, it has nothing to do with the storage location of elements in the container.

3. Map type

When defining a map object, you must specify the key and value types respectively. When using the associated container, its key not only has a type, but also has a related comparison function. By default, the standard library uses the operator defined by the key type to compare keys. The comparison function used must be defined on the key type.Strictly weak sorting. The so-called weak sorting can be understood as the "less than" relationship on key-type data. Although you can choose to make the comparison function more complex. However, no matter how such a comparison function is defined, when used for comparing a key with itself, it will certainly result in false results. In addition, when comparing two keys, there cannot be mutual "less than", And If k1 "less than" K2, K2 "less than" K3, then K1 must be "less than" K3. If the two keys do not have a "less than" relationship between them, the container regards them as the same key. When using the key as the map object, you can use any key value to access the corresponding element.

 

Map-defined types

Map <K, V >:: key_type in the map container, the type of the key used for Indexing

Map <K, V >:: mapped_type in the map container, the type of the value associated with the key

Map <K, V >:: value_type is a pair type. Its first element has the const _ Map <K, V >:: key_type type, while the second element is the map <K, v>: mapped_type

When learning the map interface, remember that value_type is of the pair type. Its value members can be modified, but the key members cannot be modified.

The map iterator will produce pair-type objects for unreferencing.

 

Add elements to map

A. accessing a map object using a subscript is different from accessing an array or vector using a subscript. Accessing a nonexistent element using a subscript causes a new element to be added to the map container, its key is the value of the lower mark. Value Initialization is used for the associated values: the elements of the class type are initialized using the default constructor, and the elements of the built-in type are initialized to 0.

B. MAP: Use of insert

M. insert (E)
E is a value of the value_tyep type used on M. If the key (E. First) is not m, a new element with the value of E. Second is inserted. If the key already exists in m, m remains unchanged. This function returns a pair type object, containing the map iterator pointing to the element of the E. First key, and a bool type object, indicating whether the element is inserted. If the key is already in the container, the associated value remains unchanged, and the returned bool value is false. If the key is not in the container, a new element is inserted, and the bool value is true.

M. insert (beg, end) beg and end are iterators marking the element range. The elements must be M. value_type key-value pairs. For all elements in the range, if its key does not exist in m, insert the key and its associated values to M. Returns the void type.

M. insert (ITER, e) E is a value_type value used on M. If the key (E. First) is not in m, create a new element and search for the location of the new element storage from the iterator ITER. Returns an iterator pointing to an element with a given key in M.

The real parameters passed by p313 to insert are clumsy and can be simplified using make_pair or typedef.

 

The map container, which finds and reads the element in the map, provides two operations: Count and find. It is used to check whether a key exists without inserting the key.

M. Count (k) returns the number of K occurrences in M.

M. Find (k) If the m container contains an element indexed by K, the iterator pointing to the element is returned. If it does not exist, the system returns the iterator that exceeds the end iterator.

 

Delete an element from a map object

M. Erase (k) deletes the elements whose key is K. Returns the size_type value, indicating the number of deleted elements.

M. Erase (p) removes the element pointed to by iterator P from M. P must point to an element that exists in m, andCannot be equal to M. End (). Returns the void type.

M. Erase (B, E) removes a range of elements from M, which are marked by the iterator for B and E. B and E must mark a valid range in M: Both B and E must point to the element in M or the next position of the last element. In addition, B and E are either equal (the deleted range is blank at this time), or the element pointed to by B appears before the element of e value. Returns the void type.

 

4. Set Type

In the set container, value_type is not the pair type, but the same type as key_type. They all refer to the element types stored in the set. The elements stored in the set are only keys, and the keys stored in the Set container must be unique and cannot be modified.

 

5. multimap and Multiset types

Allows one key to correspond to multiple instances.

The erase version with a key parameter deletes all elements with the key and returns the number of deleted elements. The version value with one or a pair of iterator parameters deletes the specified Element and returns the void type.

 

Unique iterator-oriented solutions

M. lower_bound (k) returns an iterator pointing to the first element with the key not less than K

M. upper_bound (k) returns an iterator pointing to the first element with a key greater than K.

M. ipv_range (k) returns the pair object of an iterator. Its first member is equivalent to M. lower_bound (K), while the second member is equivalent to M. upper_bound (k)

When lower_bound and upper_bound are called on the same shoulder, an iterator range is generated to indicate all the elements associated with the key. If the reconstruction is not in multimap, the two operations will return an iterator pointing to the location where the key should be inserted based on the sorting order of the elements.

These operations may return containers that exceed the end iterator. If the searched element has the largest key in the multimap container, calling upper_bound on the key will return an iterator that exceeds the end. If the searched key does not exist and is larger than all the keys in the multimap container, lower_bound will return an iterator that exceeds the end.

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.