liveBook · Manning

Push_back

As explained in Learn C++ by Example

push_back is a C++ sequence-container member function that appends an element to the container.

push_back is a C++ sequence-container member function that appends an already constructed element to the container. With std::vector, it adds the value at the end. section 2.2.2

Use push_back when:

  • You already have an object to add, such as a calculated row. section 2.2.2
  • You want to add an element at the container’s end; use insert for another position. section 2.2.2
  • You need to choose between copying an lvalue and moving a temporary through overload resolution. section 2.2.3

Building Pascal’s triangle

A generated row can be appended with triangle.push_back(data). If get_next_row(...) produces a temporary, triangle.push_back(get_next_row(triangle.back())) can use the rvalue overload and avoid copying the row. section 2.2.2 section 2.2.3

Listing 2.4 Moving a temporary
auto generate_triangle(int rows)
{
    std::vector<std::vector<int>> triangle{ {1} };    #1
    for (int row = 1; row < rows; ++row)              #2
    {
        triangle.push_back(get_next_row(triangle.back()));
    }
    return triangle;
}

Inspect the complete Pascal’s-triangle example, including push_back with a temporary row and the loop that generates successive rows. section 2.2.3

How Learn C++ by Example covers it

How deep it goes
Explains copying, rvalue overloads, moving temporaries, and the contrast with emplace_back; it defers complete value-category details.
Examples
Uses Pascal’s triangle rows, triangle.push_back(data), and push_back(get_next_row(triangle.back())) to demonstrate copying and moving.
What it assumes
Assumes basic C++ containers and objects while introducing lvalues, rvalues, overloads, and the copy-versus-move distinction.
What you can do after
Apply it via std::vector to append existing objects and recognize when an lvalue is copied or a temporary is moved.
How it connects
Connects push_back with std::vector, emplace_back, move semantics, rvalue references, and perfect forwarding.

Also explained in

Compare how 2 books explain push_back →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn C++ by Example. The section links point to the parts of the book it draws on.