In C++,vector
is a dynamic array container provided by STL (standard template library) that allows us to dynamically resize at runtime. vector provides many convenient operations, making it ideal for managing data. In this blog, we will explore some common ways to operate vectors and provide some extended knowledge to help you better understand and use this powerful data structure.
1. Initialization and assignment
1.1 Default constructor
vector<int> v1;
Create an emptyvector
。
1.2 Specify the size and initial value
vector<int> v2(5, 10);
Create a 5 elementsvector
, the initial value of each element is 10.
1.3 Initialization with list
vector<int> v3 = {1, 2, 3, 4, 5};
Use initial value list to constructvector
。
1.4 Copy constructor
vector<int> v4(v3);
Use existing onesvector
Perform copy construction.
2. Access elements
2.1 Using the [] operator
int val = v3[2];
Access elements directly through the index, but do not check boundaries.
2.2 Using the at() function
int val = (2);
and[]
Similar, butat()
It will check whether the index is legal and an exception will be thrown outside the scope.
2.3 Get the first and last elements
int first = (); int last = ();
2.4 Get pointers to data
int* data_ptr = ();
Getvector
Pointer to the array in the element.
3. Modify elements
3.1 Adding elements
3.1.1 Usepush_back()
v3.push_back(6);
existvector
Add an element at the end of .
3.1.2 Useemplace_back()
v3.emplace_back(7);
Construct an element in place at the end to avoid unnecessary copying.
3.2 Delete elements
3.2.1 Usepop_back()
v3.pop_back();
Removevector
The element at the end.
3.2.2 Useerase()
(() + 2);
Removes the element at the specified location.
3.2.3 Useclear()
();
Clearvector
All elements in.
4. Iterator operation
4.1 Use iterator to traverse
for (vector<int>::iterator it = (); it != (); ++it) { cout << *it << " "; }
4.2 Use range for loop
for (int val : v3) { cout << val << " "; }
4.3 Using a reverse iterator
for (vector<int>::reverse_iterator rit = (); rit != (); ++rit) { cout << *rit << " "; }
5. Capacity Management
5.1 Use size() and capacity()
size_t size = (); size_t capacity = ();
size()
returnvector
The number of elements incapacity()
Returns the currently allocated storage space size (number of elements that can be accommodated).
5.2 Use reserve()
(10);
Pre-allocate space that can accommodate at least 10 elements.
5.3 Use resize()
(8, 0);
Willvector
The size of the 8 is resized to 8. If the new size is greater than the current size, the extra elements will be initialized with 0.
6. Performance optimization skills
6.1 Avoid unnecessary copying
When inserting elements, try to useemplace_back()
Insteadpush_back()
, can reduce the copy construction of the object at once.
6.2 Using shrink_to_fit()
v3.shrink_to_fit();
Free up excess capacity and reduce memory usage.
6.3 Avoid over-scaling
In knownvector
When the size is approximately range, use it in advancereserve()
Allocate enough space to avoid frequent memory allocation during expansion.
7. Expand knowledge
7.1 Memory Management of vector
vector
Dynamic arrays are used to manage elements. When an extension is required, it allocates a larger memory block and copies the original elements. To avoid frequent memory allocation,vector
Usually more space is reserved than it actually needs, and that's whatcapacity()
andsize()
The difference between.
7.2 Exceptional security
vector
Many operations such aspush_back()
、resize()
etc, new memory may be allocated and objects may be moved. Therefore, in operationvector
Exception safety should be considered when it comes to this. In most cases,vector
What is provided is a "strong exception security guarantee", that is, if an exception occurs, the state of the container will not be destroyed.
7.3 Comparison with original array
vector
Provides dynamic resizing, automatic memory management, and many convenient operations, while raw arrays are simpler and slightly more performant. Where efficient memory usage is required, you can consider using itstd::array
or original array, but in most cases,vector
It is a safer and more flexible choice.
This is the article about the common operation methods of vectors in C++. For more related C++ vector operations, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!