C ++ STL 2: Container vector Summary

Source: Internet
Author: User




I. Container vector

When using vector, the header file must be included. <vector>:

# Include <vector>

Type vector is a template defined in namespace std:


[Cpp]
Template <class _ Ty,
Class _ Ax = allocator <_ Ty>
Template <class _ Ty,
Class _ Ax = allocator <_ Ty> the second parameter defines the memory model. We generally use the default memory model.

 


Ii. Functions of vector

Vector is molded into a dynamic array. Vector copies its element to an internal dynamic array. There is always an order between elements. It is an ordered cluster. Supports instant access. Its iterator is a random access iterator, so it works for any STL algorithm.

Add an element to the vector or delete one of the elements. All the elements after the element must be moved, and the value assignment operator must be called for each move. Therefore, it has good performance to add or delete elements at the end. However, in the front or middle part, the performance is poor.

One of the secrets of vector's excellent performance is that it requires more memory than its contained elements. We need to know the relationship between size and capacity.

The function size () returns the vector size, that is, the number of actual elements in the vector.

Capacity () returns the capacity, which is the number of elements that the current vector can actually accommodate. It should always be greater than or equal to the vector size. If you want to place more elements than capacity in a vector, You need to reconfigure the internal memory. The capacity of the vector will also increase. See the following sample code:


[Cpp]
# Include <iostream>
# Include <vector>
# Include <string>
# Include <algorithm>
Using namespace std;
 
Int main ()
{
Vector <string> sentence (1 );
Cout <"max_size ():" <sentence. max_size () <endl;
Cout <"size ():" <sentence. size () <endl;
Cout <"capacity ():" <sentence. capacity () <endl;
 
Sentence. reserve (5 );
 
Sentence. push_back ("Hello ,");
Sentence. push_back ("how ");
Sentence. push_back ("are ");
Sentence. push_back ("you ");
Sentence. push_back ("? ");
 
Copy (sentence. begin (), sentence. end (),
Ostream_iterator <string> (cout ,""));
Cout <endl;
 
Cout <"max_size ():" <sentence. max_size () <endl;
Cout <"size ():" <sentence. size () <endl;
Cout <"capacity ():" <sentence. capacity () <endl;
 
Swap (sentence [1], sentence [3]);
 
Sentence. insert (find (sentence. begin (), sentence. end (),"? "),
"Always ");
 
Sentence. back () = "! ";
 
Copy (sentence. begin (), sentence. end (),
Ostream_iterator <string> (cout ,""));
 
Cout <endl;
 
Cout <"max_size ():" <sentence. max_size () <endl;
Cout <"size ():" <sentence. size () <endl;
Cout <"capacity ():" <sentence. capacity () <endl;
}
# Include <iostream>
# Include <vector>
# Include <string>
# Include <algorithm>
Using namespace std;

Int main ()
{
Vector <string> sentence (1 );
Cout <"max_size ():" <sentence. max_size () <endl;
Cout <"size ():" <sentence. size () <endl;
Cout <"capacity ():" <sentence. capacity () <endl;

Sentence. reserve (5 );

Sentence. push_back ("Hello ,");
Sentence. push_back ("how ");
Sentence. push_back ("are ");
Sentence. push_back ("you ");
Sentence. push_back ("? ");

Copy (sentence. begin (), sentence. end (),
Ostream_iterator <string> (cout ,""));
Cout <endl;

Cout <"max_size ():" <sentence. max_size () <endl;
Cout <"size ():" <sentence. size () <endl;
Cout <"capacity ():" <sentence. capacity () <endl;

Swap (sentence [1], sentence [3]);

Sentence. insert (find (sentence. begin (), sentence. end (),"? "),
"Always ");

Sentence. back () = "! ";

Copy (sentence. begin (), sentence. end (),
Ostream_iterator <string> (cout ,""));

Cout <endl;

Cout <"max_size ():" <sentence. max_size () <endl;
Cout <"size ():" <sentence. size () <endl;
Cout <"capacity ():" <sentence. capacity () <endl;
} Running result:


 

In the program, when an element is inserted into the vector again, the memory is re-allocated because the vector capacity is insufficient. However, the results of capacity () are related to the actual version, and max_size is the same.

 


The vector capacity is very important because:

1. Once the memory is reconfigured, all reference, pointers, and iterators related to the memory will become invalid.

2. Memory configuration is time-consuming.

The solutions to this problem are:

1. You can use reserve () to retain the appropriate capacity to reduce the number of times the memory is reconfigured. Sample Code:


[Cpp]
Vector <string> sentence (1 );
Sentence. reserve (50 );
Vector <string> sentence (1 );
Sentence. reserve (50); 2. assign additional parameters to the constructor during initialization to create sufficient space.
[Cpp]
Vector <T> v (5 );
Vector <T> v (5); of course, the type of this element must provide the default constructor. However, Initialization is time-consuming if the type of the element is complex. If you only want to retain enough memory, use method 1 is better.

Note: reserve cannot reduce the vector capacity. As a result, we can know that even if an element is deleted, its reference, pointers, and iterators will continue to be valid, pointing to the position before the action.

However, the insert operation may invalidate reference, pointers, and iterators (because space may be reconfigured ).

 


The swap function can reduce the vector capacity. Because after two vectors exchange content, their capacity will also change.

1,


[Cpp]
Template <class T>
Void shrinkCapacity (vector <T> & v)
{
Vector <T> tmp (v );
V. swap (tmp );
}
Template <class T>
Void shrinkCapacity (vector <T> & v)
{
Vector <T> tmp (v );
V. swap (tmp );
} 2,
[Cpp]
Vector <T> (v). swap (v );
Vector <T> (v). swap (v); the above two methods are equivalent. Www.2cto.com
A temporary vector object is constructed first, initialized with the v element, and exchanged with v. Note that temporary objects are generally precisely allocated with the actual memory required. Therefore, it can reduce the vector capacity.

 


3. vector Operation Functions

All constructors and destructor are as follows:

 


 

Non-variable operations:

 


 

Assignment operation:

 


 

The preceding operation assigns a new element to the vector and removes all the old elements! Sample Code:


[Cpp]
# Include <iostream>
# Include <vector>
# Include <string>
# Include <algorithm>
Using namespace std;
 
Int main ()
{
Vector <string> sentence (1 );
Cout <"max_size ():" <sentence. max_size () <endl;
Cout <"size ():" <sentence. size () <endl;
Cout <"capacity ():" <sentence. capacity () <endl;
 
Sentence. reserve (5 );
 
Sentence. push_back ("Hello ,");
Sentence. push_back ("how ");
Sentence. push_back ("are ");
Sentence. push_back ("you ");
Sentence. push_back ("? ");
 
Copy (sentence. begin (), sentence. end (),
Ostream_iterator <string> (cout ,""));
Cout <endl;
 
Sentence. assign (3, "new ");
 
Copy (sentence. begin (), sentence. end (),
Ostream_iterator <string> (cout ,""));
Cout <endl;
}
# Include <iostream>
# Include <vector>
# Include <string>
# Include <algorithm>
Using namespace std;

Int main ()
{
Vector <string> sentence (1 );
Cout <"max_size ():" <sentence. max_size () <endl;
Cout <"size ():" <sentence. size () <endl;
Cout <"capacity ():" <sentence. capacity () <endl;

Sentence. reserve (5 );

Sentence. push_back ("Hello ,");
Sentence. push_back ("how ");
Sentence. push_back ("are ");
Sentence. push_back ("you ");
Sentence. push_back ("? ");

Copy (sentence. begin (), sentence. end (),
Ostream_iterator <string> (cout ,""));
Cout <endl;

Sentence. assign (3, "new ");

Copy (sentence. begin (), sentence. end (),
Ostream_iterator <string> (cout ,""));
Cout <endl;
} Running result:



 

We can see that all the original elements have been deleted.


Element access

 


 

Among these functions, the only subscript check is the at function.

Therefore, when calling operator [], you must be clear about whether the index is valid.

 


Iterator-related functions

 


 

Two failures of the iterator are:

1. delete or move an element in a small position.

2. Memory reallocation due to capacity change.

 


Insert and remove elements

 


 

Inserting and removing elements will invalidate the reference, pointers, and iterators of each element after "vertex. The insert operation may also cause memory reallocation, so all references, pointers, and iterators on the container will become invalid.

 


4. Use vector as a general Array

The current C ++ standard ensures that the elements of a vector must be distributed in a continuous space. A valid index in a vector must meet the following expressions:

& V [I] = & v [0] + I;

We must ensure that the vector can accommodate all the data. If C-String is used, remember that there is '\ 0' at the end '.

If we need an array whose element type is T, we can use vector <T> and then pass the address of the first element to it.

Note: never use the iterator as the address of the first element. Because the vector iterator is defined by the actual version, it is not necessarily a general pointer.


[Cpp]
Printf ("% s", v. begin (); // ERROR (might work, but not portable)
Printf ("% s", & v [0]); // OK
Printf ("% s", v. begin (); // ERROR (might work, but not portable)
Printf ("% s", & v [0]); // OK



From Yanyu, Jiangnan

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.