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

The C++ container class

The C++ container class

Introduction

The C++ Standard Template Library (STL) is an important part of C++; it provides a set of general-purpose template classes and functions for handling data collections. is a container class in the STL, used to store dynamically-sized arrays.

is a sequence container that allows users to quickly add or remove elements at the end of the container. Compared with arrays, provides more functionality, such as automatic resizing, random access, etc.

Syntax

In C++, to use , you need to include the header <>. Here is some basic syntax:

Declaration and initialization

requires specifying the element type; it can be initialized in several ways:

#include 

#include 



int main() {

    std::vector vec1;                  // 空的vector

    std::vector vec2(5);               // 长度为5的vector,元素默认初始化

    std::vector vec3(5, 10);           // 长度为5的vector,元素值为10

    std::vector vec4 = {1, 2, 3, 4};   // 使用初始化列表初始化



    return 0;

}

Example

Below is an example using with its output.

Example

#include

#include

int

main

(

)

{

   

// Declare a vector storing integers

    std

::

vector

<

int

numbers

;

   

// Add elements

    numbers.

push_back

(

10

)

;

    numbers.

push_back

(

20

)

;

    numbers.

push_back

(

30

)

;

   

// Output the elements in the vector

    std

::

cout

<<

"Vector contains: "

;

   

for

(

int

i

=

0

;

i

<

numbers.

size

(

)

;

++

i

)

{

        std

::

cout

<<

numbers

[

i

]

<<

" "

;

   

}

    std

::

cout

<<

std

::

endl

;

   

// Add more elements

    numbers.

push_back

(

40

)

;

    numbers.

push_back

(

50

)

;

   

// Output the elements in the vector again

    std

::

cout

<<

"After adding more elements, vector contains: "

;

   

for

(

int

i

=

0

;

i

<

numbers.

size

(

)

;

++

i

)

{

        std

::

cout

<<

numbers

[

i

]

<<

" "

;

   

}

    std

::

cout

<<

std

::

endl

;

   

// Access a specific element

    std

::

cout

<<

"The first element is: "

<<

numbers

[

0

]

<<

std

::

endl

;

   

// Clear the vector

    numbers.

clear

(

)

;

   

// Check whether the vector is empty

   

if

(

numbers.

empty

(

)

)

{

        std

::

cout

<<

"The vector is now empty."

<<

std

::

endl

;

   

}

   

return

0

;

}

Output result:



Vector contains: 10 20 30 

After adding more elements, vector contains: 10 20 30 40 50 

The first element is: 10 

The vector is now empty.


Common member functions

The following are of include the following commonly used member functions:

function Description
push_back(const T& val) add an element at the end
pop_back() remove the last element
at(size_t pos) returns the element at the specified position, with bounds checking
operator[] returns the element at the specified position, without bounds checking
front() returns the first element
back() returns the last element
data() returns a pointer to the underlying array
size() return the current number of elements
capacity() return the currently allocated capacity
reserve(size_t n) reserve at least n elements' storage space
resize(size_t n) adjust the number of elements to n
clear() clears all elements
insert(iterator pos, val) inserts an element at a specified position
erase(iterator pos) Remove the element at a specified position
begin()/ end() return the begin/end iterators

Example

1. Basic operations

Example

#include

#include

int

main

(

)

{

    std

::

vector

<

int

vec

=

{

1

,

2

,

3

,

4

,

5

}

;

   

// Output all elements

    std

::

cout

<<

"Vector elements: "

;

   

for

(

int

i

=

0

;

i

<

vec.

size

(

)

;

++

i

)

{

        std

::

cout

<<

vec

[

i

]

<<

" "

;

   

}

    std

::

cout

<<

std

::

endl

;

   

// Get the first and last elements

    std

::

cout

<<

"First element: "

<<

vec.

front

(

)

<<

std

::

endl

;

    std

::

cout

<<

"Last element: "

<<

vec.

back

(

)

<<

std

::

endl

;

   

return

0

;

}

2. Dynamically add and remove elements

Example

#include

#include

int

main

(

)

{

    std

::

vector

<

int

vec

;

    vec.

push_back

(

10

)

;

    vec.

push_back

(

20

)

;

    vec.

push_back

(

30

)

;

    std

::

cout

<<

"Vector size: "

<<

vec.

size

(

)

<<

std

::

endl

;

    std

::

cout

<<

"Vector capacity: "

<<

vec.

capacity

(

)

<<

std

::

endl

;

   

// Delete the last element

    vec.

pop_back

(

)

;

    std

::

cout

<<

"After pop_back, size: "

<<

vec.

size

(

)

<<

std

::

endl

;

   

return

0

;

}

3. Bounds checking and safe access

Example

#include

#include

int

main

(

)

{

    std

::

vector

<

int

vec

=

{

1

,

2

,

3

}

;

   

try

{

        std

::

cout

<<

vec.

at

(

2

)

<<

std

::

endl

;

 

// Normal output

        std

::

cout

<<

vec.

at

(

5

)

<<

std

::

endl

;

 

// Out of range, throws exception

   

}

catch

(

const

std

::

out_of_range

&

e

)

{

        std

::

cout

<<

"Exception: "

<<

e.

what

(

)

<<

std

::

endl

;

   

}

   

return

0

;

}

4. Pre-allocate capacity

Example

#include

#include

int

main

(

)

{

    std

::

vector

<

int

vec

;

    vec.

reserve

(

10

)

;

 

// Reserve capacity to avoid frequent memory allocation

   

for

(

int

i

=

0

;

i

<

10

;

++

i

)

{

        vec.

push_back

(

i

)

;

        std

::

cout

<<

"Capacity after push_back("

<<

i

<<

"): "

<<

vec.

capacity

(

)

<<

std

::

endl

;

   

}

   

return

0

;

}

Comparison with other containers

Feature std::vector std::array std::list
Size Dynamically variable Fixed at compile time Dynamically variable
Storage location Contiguous memory Contiguous memory Non-contiguous memory
Access performance Fast random access Fast random access Slow random access, suitable for sequential access
Insertion and deletion performance High performance at the end, slower at other positions Not supported Faster insertion and deletion at any position
Memory growth pattern Doubles when capacity is insufficient None None

is a very useful container in the C++ STL; it provides dynamic array functionality, making the addition and removal of elements more flexible and convenient. Through the above examples, beginners can quickly understand 's basic usage and operations. As you delve deeper into learning, you will discover 's powerful features and wide application in real programming.