Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

C++ vector Container

C++ vector Container

In C++,vector is one of the most commonly used STL containers.

vector is essentially adynamically resizable array. Compared with traditional arrays, vector does not require manual memory management and can automatically grow according to the number of elements.

Because vector has:

Therefore, in modern C++ development, vector is the preferred choice for most sequential data storage scenarios.

Core Features of vector

Why is vector fast?

The elements of a vector are arranged contiguously in memory:


[1][2][3][4][5]

This layout is very cache-friendly for the CPU.

When the CPU reads the first element, it usually preloads the following data into the cache, so iterating over a vector is usually very fast.

This is also why in many cases:


vector 比 list 更快

even though list has a theoretically lower deletion complexity.

Using vector

Before using vector, you need to include the header file:


#include 

Creating a vector

Create an empty vector:


std::vectorvec;

Specify an initial size:


std::vectorvec(5);

The code above creates 5 elements with a default value of 0.

Specify an initial value:


std::vectorvec(5, 10);

Creation result:


[10, 10, 10, 10, 10]

Using an initializer list:


std::vectorvec = {1, 2, 3, 4};

Adding elements

Use push_back() Add elements to the tail:


vec.push_back(100);

The average time complexity of appending an element to the tail of a vector is:


O(1)

Accessing elements

Access using an index:


int x = vec[0];

Use at():


int y = vec.at(1);

Difference:

Getting the size


vec.size();

Returns the current number of elements.

The difference between size and capacity

This is one of the most important concepts of vector.


std::vectorvec;

vec.push_back(1);
vec.push_back(2);

std::cout << vec.size() << std::endl;
std::cout << vec.capacity() << std::endl;

The output may be:


2
4

capacity is usually greater than or equal to size.

This is because vector requests extra space in advance to reduce frequent reallocations.

vector Reallocation Mechanism

When a vector runs out of space, reallocation occurs:

  1. allocate larger memory
  2. copy old elements
  3. free old memory

This process is costly.

For example:


std::vectorvec;

for (int i = 0; i < 1000000; i++) {
    vec.push_back(i);
}

Multiple memory reallocations may occur.

reserve() to preallocate space

To avoid frequent reallocations, you can allocate memory in advance:


std::vectorvec;

vec.reserve(1000000);

This reduces:

This is a very important optimization technique in engineering development.

Iterating over a vector

Using an index


for (size_t i = 0; i < vec.size(); i++) {
    std::cout << vec[i] << " ";
}

Using an iterator


for (auto it = vec.begin(); it != vec.end(); ++it) {
    std::cout << *it << " ";
}

Range-based for loop


for (int element : vec) {
    std::cout << element << " ";
}

Delete elements

Delete the third element:


vec.erase(vec.begin() + 2);

Note:

When deleting a middle element from a vector, the following elements are shifted forward as a whole.

For example:


1 2 3 4 5

After deleting 2:

1 3 4 5

Where:


3 4 5

all need to have their positions shifted.

Therefore:


erase() 的时间复杂度为 O(n)

Scenarios Where vector Is Unsuitable

For example:


vec.insert(vec.begin(), 100);

This is a slower operation.

Iterator invalidation

After a vector reallocates, the original memory address may become invalid.

For example:


std::vectorvec = {1, 2, 3};

auto it = vec.begin();

vec.push_back(4);

std::cout << *it;

Here, it may have become invalid.

because push_back() may cause memory reallocation.

This is one of the most common pitfalls of vector.

Notes on clear()


vec.clear();

clear() only removes the elements:

That is to say:


clear() 不一定释放内存

If you want to release the memory:


std::vector().swap(vec);

or:


vec.shrink_to_fit();

push_back and emplace_back

Modern C++ recommends using:


emplace_back()

For example:


vec.push_back(Person("Tom", 20));

may produce a temporary object.

whereas:


vec.emplace_back("Tom", 20);

constructs the object in place directly inside the vector.

is usually more efficient.

Difference Between vector and Array

Feature arrays vector
fixed size Is No
automatic resizing No Is
Contiguous memory Is Is
random access fast fast
STL support less complete
safe access None at()

Common Operation Complexities of vector

Operation Time Complexity
random access O(1)
push_back average O(1)
tail deletion O(1)
head insertion O(n)
middle deletion O(n)
clear O(n)

Example: Student Grade Management

Example

#include

#include

#include

int

main

(

)

{

    std

::

vector

<
int
scores
=
{
85
,
90
,
78
,
92
}

;

    scores.

push_back

(

88

)

;

    std

::

cout

<<

"All grades: "

;

   

for

(

int

score

:

scores

)

{

        std

::

cout

<<

score

<<

" "

;

   

}

    std

::

cout

<<

std

::

endl

;

   

int

total

=

std

::

accumulate

(

scores.

begin

(

)

, scores.

end

(

)

,

0

)

;

   

double

average

=

total

1.0

/

scores.

size

(

)

;

    std

::

cout

<<

"Average grade: "

<<

average

<<

std

::

endl

;

    scores.

erase

(

scores.

begin

(

)

2

)

;

    std

::

cout

<<

"Grades after deletion: "

;

   

for

(

int

score

:

scores

)

{

        std

::

cout

<<

score

<<

" "

;

   

}

    std

::

cout

<<

std

::

endl

;

   

return

0

;

}

The output is as follows:


所有成绩: 85 90 78 92 88 
平均成绩: 86.6
删除后成绩: 85 90 92 88 

Summary

vector is one of the most important and most commonly used data structures in modern C++.

Its core advantages:

but you also need to pay attention to:

For the vast majority of sequential storage scenarios:


vector 通常都是默认首选容器