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

C++ push_back function

C++ push_back function

C++ Container Class The C++ container class


Among many containers,vector (vector) is the most commonly used and most array-like one that can automatically grow, and push_back is the key function that makes this array grow.

push_back is a member function, used todynamic array (vector) orother sequence containers (such as list, deque) 'sendadd a new element.

push_backimplements the container'sdynamic growth; you do not need to specify the container's final size in advance, and can add elements anytime as needed at runtime.

Word meaning: push is push,back is back; together they mean to push to the back, which is very intuitive.


Basic syntax and parameters

push_back is a member function of the container class, so you need to have a container object first, then use the dot operator . to call it.

Syntax format



void push_back(const T& value);

void push_back(T&& value);  // C++11 之后(支持右值)

Parameter Description

- Type: Consistent with the element type specified when the container was defined, or a value that can be converted to that type. - Description: The value you want to add to the end of the container. It can be a variable, a literal (such as `10`, `"hello"`), or the result of an expression.

Function description


Example

Let us thoroughly master push_back through a series of examples from simple to complex.

Example 1: Basic usage - managing integers

Example

#include

#include // 1. Must include the vector header

int

main

(

)

{

   

// 2. Create an empty vector for storing integers

    std

::

vector

<

int

numbers

;

    std

::

cout

<<

"Initially, the size of the vector is: "

<<

numbers.

size

(

)

<<

std

::

endl

;

   

// 3. Use push_back to add elements

    numbers.

push_back

(

10

)

;

// Add integer 10 at the end

    numbers.

push_back

(

20

)

;

// Add 20 after 10

    numbers.

push_back

(

30

)

;

// Add 30 after 20

    std

::

cout

<<

"After adding, the size of the vector is: "

<<

numbers.

size

(

)

<<

std

::

endl

;

   

// 4. Traverse and output all elements to verify the addition order

    std

::

cout

<<

"The elements in the vector are: "

;

   

for

(

int

i

=

0

;

i

<

numbers.

size

(

)

;

++

i

)

{

        std

::

cout

<<

numbers

[

i

]

<<

" "

;

// Access by index like an array

   

}

    std

::

cout

<<

std

::

endl

;

   

return

0

;

}

Expected output:

初始时,vector的大小是: 0

添加后,vector的大小是: 3

vector中的元素是: 10 20 30

Code analysis:

  1. #include is the prerequisite for using vector the container.
  2. std::vector numbers; creates a numbers empty vector, which will store in the future int integers of type.
  3. three times push_back calls, sequentially adding 10, 20, 30 to numbers 's end. The addition order is the final order of elements in vector .
  4. numbers.size() returns the current element count.numbers[i] uses index to access elements, consistent with array usage.

Example 2: Managing strings

vector can store not only numbers but also strings, custom types, and any other data type.

Example

#include

#include

#include // Using string also requires including the header

int

main

(

)

{

   

// Create a vector storing std::string

    std

::

vector

<

std

::

string

tasks

;

   

// Use push_back to add to-do items

    tasks.

push_back

(

"Learn C++ push_back"

)

;

    tasks.

push_back

(

"Do homework"

)

;

    tasks.

push_back

(

"Read technical documentation"

)

;

    std

::

cout

<<

"Today's to-do items ("

<<

tasks.

size

(

)

<<

" items):\n"

;

   

// Use the range-based for loop (C++11) to traverse, more concise

   

for

(

const

auto

&

task

:

tasks

)

{

        std

::

cout

<<

"- "

<<

task

<<

std

::

endl

;

   

}

   

return

0

;

}

Expected output:

今日待办事项 (3 项):

- 学习 C++ push_back

- 写作业

- 阅读技术文档

Code analysis:

Example 3: Dynamically build container content

This is push_back the most powerful part: building containers based on runtime data (such as user input, file reading).

Example

#include

#include

int

main

(

)

{

    std

::

vector

<

int

scores

;

   

int

inputScore

;

   

char

continueFlag

=

'y'

;

    std

::

cout

<<

"Please enter student grades (enter a non-number to end):\n"

;

   

// Method 1: decide the loop based on user input

   

while

(

std

::

cin

inputScore

)

{

        scores.

push_back

(

inputScore

)

;

   

}

   

// Clear cin's error state for possible subsequent input

    std

::

cin

.

clear

(

)

;

    std

::

cin

.

ignore

(

10000

,

'\n'

)

;

   

// Method 2: ask whether to continue

   

/*
    while(continueFlag == 'y' || continueFlag == 'Y') {
        std::cout << "Please enter a score: ";
        std::cin >> inputScore;
        scores.push_back(inputScore);

        std::cout << "Continue entering? (y/n): ";
        std::cin >> continueFlag;
    }
    */

    std

::

cout

<<

"\nTotal entered "

<<

scores.

size

(

)

<<

" grades.\n"

;

   

if

(

!

scores.

empty

(

)

)

{

// Check whether the container is empty

       

int

sum

=

0

;

       

for

(

int

score

:

scores

)

{

            sum

=

score

;

       

}

        std

::

cout

<<

"Average is: "

<<

static_cast

<

double

(

sum

)

/

scores.

size

(

)

<<

std

::

endl

;

   

}

   

return

0

;

}

This example shows how to use push_back dynamically fill the container in a loop and finally calculate the average. You can try running and entering 100 90 85 a(finally enter a letter a to end the number input loop).


C++ Container Class The C++ container class