C++ <vector> push_back Function

C++ container class <vector>


Among the many containers,vector(vector) is the most commonly used one and the one most like an automatically expandable array, whilepush_backis the key function that makes this array expandable.

push_backis a member function used todynamic arrays (vector)orOther sequence containers (such aslist, deque)ofendadd a new element.

push_backimplement the container'sdynamic growth, you don't need to pre-specify the container's final size; you can add elements at any time as needed during program runtime.

Word Definitions: pushis pushing,backis "back/push," so together it means "push to the back" — very intuitive.


basic syntax and parameters

push_backis a member function of container classes, so you need to first have a container object, 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

  • Parameter: value
    • Type: the same as 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 as10, "hello"), or the result of an expression.

Function description

  • Return Value: void(no return value). Its purpose is purely to "add an element"; once the addition is complete, the function ends.
  • Effect: of the containersize()(current element count) increases by 1. The new element becomes the last element of the container.

Example

Let us thoroughly master this through a series of examples ranging from simple to complex.push_backUsage.

Example 1: Basic usage — managing integers

Example

#include <iostream>
#include <vector> // 1. Must include the vector header file

int main() {
    // 2. Create an empty vector to store 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 order of addition
    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 <vector>is to usevectorthe prerequisite of the container.
  2. std::vector<int> numbers;created one namednumbersof the emptyvector, which will in the future storeintintegers of type.
  3. three timespush_backcall, sequentially10, 20, 30add tonumbersat the end. The order of addition is the order in which elements arevectorthe final order in.
  4. numbers.size()returns the current number of elements.numbers[i]Use subscripts to access elements, just like array usage.

Example 2: Managing strings

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

Example

#include <iostream>
#include <vector>
#include <string> // You also need to include the header file to use string

int main() {
    // Create a vector that stores 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() << " item):\n";
    // Use range-based for loop (C++11) to traverse, which is more concise
    for(const auto& task : tasks) {
        std::cout << "- " << task << std::endl;
    }

    return 0;
}

Expected output:

今日待办事项 (3 项):
- 学习 C++ push_back
- 写作业
- 阅读技术文档

Code analysis:

  • std::vector<std::string>declares the element type asstd::stringcontainer.
  • push_backThe parameter is now a string literal (which is automatically converted tostd::string)。
  • for(const auto& task : tasks)is the "range-based for loop" introduced in C++11; it automatically iterates overtaskseach element in it is very convenient.autolet the compiler automatically deducetasktype.

Example 3: Dynamically building container contents

This ispush_backThe most powerful aspect: building containers based on runtime data (such as user input, file reads).

Example

#include <iostream>
#include <vector>

int main() {
    std::vector<int> scores;
    int inputScore;
    char continueFlag = 'y';

    std::cout << "Please enter student scores (enter a non-digit to end):\n";
    // Method 1: Determine the loop based on user input
    while(std::cin >> inputScore) {
        scores.push_back(inputScore);
    }

    // Clear cin's error state to allow 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 input? (y/n): ";
        std::cin >> continueFlag;
    }
    */


    std::cout << "\nA total of " << scores.size() << " scores.\n";
    if(!scores.empty()) { // Check if the container is empty
        int sum = 0;
        for(int score : scores) {
            sum += score;
        }
        std::cout << "Average score: " << static_cast<double>(sum) / scores.size() << std::endl;
    }

    return 0;
}

This example shows how to usepush_backdynamically fill a container in a loop, and finally calculate the average. You can try running it and enter100 90 85 a(finally enter a letterato end the number input loop).


C++ container class <vector>

other extensions