SoFunction
Updated on 2025-03-03

Summary of common operation methods of vector in C++

In C++,vectoris 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 onesvectorPerform 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 = ();

GetvectorPointer to the array in the element.

3. Modify elements

3.1 Adding elements

3.1.1 Usepush_back()

v3.push_back(6);

existvectorAdd 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();

RemovevectorThe element at the end.

3.2.2 Useerase()

(() + 2);

Removes the element at the specified location.

3.2.3 Useclear()

();

ClearvectorAll 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()returnvectorThe 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);

WillvectorThe 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 knownvectorWhen 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

vectorDynamic 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,vectorUsually more space is reserved than it actually needs, and that's whatcapacity()andsize()The difference between.

7.2 Exceptional security

vectorMany operations such aspush_back()resize()etc, new memory may be allocated and objects may be moved. Therefore, in operationvectorException safety should be considered when it comes to this. In most cases,vectorWhat 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

vectorProvides 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::arrayor original array, but in most cases,vectorIt 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!