C ++ study notes 5 Containers and Study Notes containers

Source: Internet
Author: User

C ++ study notes 5 Containers and Study Notes containers

1. Use assign

The assign operation first deletes all elements in the container, and then inserts the new elements specified by its parameters into the container. Like the constructor for copying container elements, if the two containers have the same type, their meta

If the element type is the same, you can use the value assignment operator (=) to assign a value to another container. If the element types are different but compatible with each other in different (or the same) types of containers

The assign function is required. For example, you can use the assign operation to assign a char * element in a vector container to a string list container.

 

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.

 

2. An important question about swap is that this operation does not delete or insert any elements, and ensures exchange within the constant time. The iterator does not expire because no elements are moved in the container.

 

3. Capacity vs size

It is important to figure out the difference between container capacity (capacity) and size (length. 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.

 

Sample:

To illustrate the interaction between size and capacity, consider the following program:

Vector <int> ivec;

 

// Size shocould bezero; capacity is implementation defined

Cout <"ivec: size:" <ivec. size () <"capacity:" <ivec. capacity () <endl;

 

// Give ivec 24 elements

For (vector <int >:: size_type ix = 0; ix! = 24; ++ ix)

Ivec. push_back (ix );

 

// Size shocould be 24; capacity will be> = 24 and isimplementation defined

Cout <"ivec: size:" <ivec. size () <"capacity:" <ivec. capacity () <endl;

 

When running the program on our system, the following output is displayed:

Ivec: size: 0 capacity: 0

Ivec: size:24Capacity:32

4. Container Selection

The program that uses these operations will decide which type of container should be selected. The vector and deque containers provide fast and Random Access to elements, but the cost is to insert or

Deleting an element is more costly than inserting or deleting an element at the end of the container. The list type can be quickly inserted and deleted at any location, but the cost is that the random access overhead of elements is large.

 

For a vector container, the insert (or delete) operation at any position except the tail of the container requires moving all the elements on the right of the inserted (or deleted) element. For example, assume that one has 50

Element. If we want to delete element 23rd, all elements after element 23 must move forward to a position. Otherwise, a blank space will be left in the vector container.

(Hole), and the elements of the vector container are no longer stored continuously.

The deque container has a more complex data structure. You can quickly insert and delete elements from both ends of the deque queue. Insert or delete a container at a higher cost. The deque container also provides

Some Properties of list and vector:

• Like a vector container, insert or erase elements in the deque container are less efficient.

• Unlike the vector container, the deque container provides efficient insert and erase operations in its header, just like at the end of the container.

• Similar to the vector container, unlike the list container, the deque container supports random access to all elements.

• Inserting an element at the beginning or end of the deque container does not invalidate any iterator. Deleting an element at the beginning or end only invalidates the iterator pointing to the deleted element. Insert and delete operations at any other location of the deque container will invalidate all iterators pointing to the container element.

 

5. How element access affects container selection

Both the vector and deque containers support efficient random access to their elements. That is to say, we can efficiently access element 5 first, then access element 15, then access element 7, and so on.

Since each access to a vector container is a fixed offset from its starting point, its random access is very efficient. In the list container, the above jump access will become much slower. In the list container's

The only way to move between elements is to follow the pointer in sequence. Moving from element 5 to element 15 must traverse all the elements between them.

 

Generally, the vector container is the best choice unless you find a better reason to use other containers.

 

6. container selection prompt

The following lists some rules for selecting the container type:

1. If the program requires Random Access to elements, the vector or deque container should be used.

2. If the program must insert or delete elements in the middle of the container, the list container should be used.

3. If the program is not in the middle of the container, but inserts or deletes elements in the header or tail of the container, deque container should be used.

4. if you only need to insert elements in the middle of the container when reading the input, and then randomly access the elements, you can consider reading the elements into a list container during the input, and then re-sorting the container, make it suitable for sequential access, and then copy the sorted list container to a vector container.

What should I do if the program needs random access and must insert or delete elements in the middle of the container?

In this case, the selected container depends on the relative cost of the following two operations: the cost of Random Access to the elements of the list container, and the cost of copying elements when inserting/deleting elements in the vector or deque container.

Generally, the dominant operations in an application (the program uses more access operations or insert/delete operations) will determine what type of containers should be. Decide which container to use may require profiling of the performance of various operations required by various container types to complete the application.

 

If you cannot determine which container should be used by an application, write the code and try to use only the operations provided by the vector and lists containers: Use the iterator instead of the subscript, and avoid random element access. In this way, you can easily change the program from a vector container to a list container when necessary.

7. Differences between the string type and the vector container

The string type is different from the vector container. It does not support stack-based container operations: the front, back, And pop_back operations cannot be used in the string type.

 

String supports the following container operations:

• Iterator type.

• Container constructor, but does not include constructor that only requires one length parameter.

• Add element operations provided by the vector container. Note: No matter the vector container or string type, the push_front operation is not supported.

• Length operation.

• Subscripts and at operations; however, the string type does not provide back and front operations listed in this table.

• Begin and end operations.

• Erase and clear operations, but the string type does not provide pop_back or pop_front operations.

• Assign values.

• String characters are stored continuously like the elements in the vector container. Therefore, the string type supports capacity and reserve operations.

 

Char * cp = "Hiya"; // null-terminated array

Char c_array [] = "World !!!! "; // Null-terminated

Char no_null [] = {'h', 'I'}; // notnull-terminated

 

String s1 (cp); // s1 = "Hiya"

String s2 (c_array, 5); // s2 = "World"

String s3 (c_array + 5, 4); // s3 = "!!!! "

String s4 (no_null); // runtime error: no_null not null-terminated

String s5 (no_null, 2); // OK: s5 = "Hi"

String s6 (s1, 2); // s6 = "ya"

String s7 (s1, 0, 2); // s7 = "Hi"

String s8 (s1, 0, 8); // s8 = "Hiya"

 

8. append and replace functions

String s ("C ++ Primer"); // initialize s to "C ++ Primer"

S. append ("3rdEd."); // s = "C ++ Primer 3rd Ed ."

// Equivalent tos. append ("3rd Ed .")

S. insert (s. size (), "3rd Ed .");

// Starting atposition 11, erase 3 characters and then insert "4th"

S. replace (11, 3, "4th"); // s = "C ++ Primer 4th Ed ."

// Equivalent way toreplace "3rd" by "4th"

S. erase (11, 3); // s = "C ++ Primer Ed ."

S. insert (11, "4th"); // s = "C ++ Primer 4th Ed ."

The replace operation is used to delete a specified range of characters and insert a group of new characters at the delete position. This operation is equivalent to calling the erase and insert functions.

S. replace (11, 3, "Fourth"); // s = "C ++ Primer Fourth Ed ."

 

9. string search operator

S. find (args) first appearance of args in s

S. rfind (args) searches for the last appearance of args in s.

S. find_first_of (args) first appearance of any character of args in s

S. find_last_of (args) finds the last occurrence of any args character in s

S. find_first_not_of (args) searches for the first character in s that does not belong to args.

S. find_last_not_of (args) searches for the last character in s that does not belong to args.

C. In s, the pos starts from the position marked by the subscript pos to find the character c. The default value of pos is 0.

S2, pos in s, search for string object s2 starting from the position marked by the subscript pos. The default value of pos is 0.

In s, the position parameter marked by the subscript pos is used to find the C-style string to which the pointer cp points. The default value of pos is 0 cp, pos, n

In s, starting from the position marked by the subscript pos, find the first n characters of the array pointed to by the pointer cp. Pos and n have no default values.

10. Summary

The C ++ standard library defines a series of sequential container types. A container is a template type used to store a given type of objects. In an ordered container, all elements are arranged and accessed according to their locations. Sequential container sharing 1

Standardized APIs for a group: if both sequential containers provide an operation, the Operation has the same interface and meaning. All containers provide (effective) dynamic memory management. Programmers in containers

When adding elements, you do not have to worry about where the elements are stored. Containers manage their own storage.

 

The most frequently used container type is vector, which supports fast Random Access to elements. You can efficiently add and delete elements at the end of the vector container, and insert or delete operations at any other location are expensive. The deque class is similar to the vector class, but it also supports fast insert and delete operations in the deque header. The list class only supports sequential access to elements, but it is very fast to insert or delete elements anywhere in the list.

 

Few operations are defined by the container. Only constructors, operations for adding or deleting elements, operations for setting the container length, and operations for returning the iterator pointing to special elements are defined. Some other useful operations, such as sorting and searching, are defined not by the container type, but by the standard algorithm described in Chapter 11th.

 

Adding or deleting elements in a container may invalidate an existing iterator. When you use the iterator operation and container operation together, you must always pay attention to whether the specified container operation will invalidate the iterator. Many

If an iterator fails, such as insert or erase, a new iterator is returned, allowing the programmer to retain a position in the container. You must be very careful with the use of its iterator for the cycle of container operations that change the container length.

 

11. When the map iterator is unreferenced, a pair-type object will be generated to unreference the iterator,

A reference pointing to a value_type value in the container is obtained. For map containers, the value_type is of the pair type:

// Get an iterator toan element in word_count

Map <string, int >:: iterator map_it = word_count.begin ();

 

// * Map_it is areference to a pair <const string, int> object

Cout <map_it-> first; // prints the key for this

Element

Cout <"" <map_it-> second; // prints the value of the element

Map_it-> first = "new key"; // error: key is const

+ Map_it-> second; // OK: wecan change value through an iterator

 

12. Programming significance of subscript Behavior

For map containers, if the keys represented by subscript do not exist in the container, add new elements. This feature can make the program incredibly concise:

// Count number oftimes each word occurs in the input

Map <string, int> word_count; // empty map from string to int

String word;

While (cin> word)

++ Word_count [word];

 

This program creates a map object to record the number of times each word appears. The while LOOP reads a word from the standard input each time. If this is a new word, add the word as the new element of the index in word_count. If the read word is already in the map object, add 1 to the corresponding value.

The most interesting thing is that when a word appears for the first time, a new element indexed by the word is inserted in word_count and its value is initialized to 0. Then, the value is immediately added with 1, so the number of occurrences of each new element added to the map starts from 1.


A container consists of three cubes, A, B, and C. The bottom area of A, B, and C is 25 cm², 10 cm², and 5 cm² respectively (1) it takes 10 seconds for the water injection process to be filled with A, and then B is filled with 8 seconds.

(2) Evaluate the hA height and water injection speed v;
Expected by question: 25hA = 10 v 10 (12-hA) = 8 v solving the equation group hA = 4 v = 10 answer A height hA4 water velocity v10.

(3) determine the time and height required for filling the container. If the C volume is y cubic centimeter
4 Y = 10 v + 8 v + yv = 10.
Y = 60
Container C Height: 60 Gb/s 5 = 12 (cm)
Therefore, container height: 12 + 12 = 24 (cm)
Full C time: 60 running v = 60 running 10 = 6 (s)
Therefore, container filling time: 10 + 8 + 6 = 24 (s ).
A container consists of three cubes, A, B, and C. The bottom area of A, B, and C is 5 cm², and C respectively (1) it takes 10 seconds for the water injection process to be filled with A, and then B is filled with 8 seconds.

(2) Evaluate the hA height and water injection speed v;
Expected by question: 25hA = 10 v 10 (12-hA) = 8 v solving the equation group hA = 4 v = 10 answer A height hA4 water velocity v10.

(3) determine the time and height required for filling the container. If the C volume is y cubic centimeter
4 Y = 10 v + 8 v + yv = 10.
Y = 60
Container C Height: 60 Gb/s 5 = 12 (cm)
Therefore, container height: 12 + 12 = 24 (cm)
Full C time: 60 running v = 60 running 10 = 6 (s)
Therefore, container filling time: 10 + 8 + 6 = 24 (s ).
I 've worked so hard to work out my homework, and I figured it out myself. I hope to adopt it.

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.