YouTip LogoYouTip

Cpp Libs Vector Push_Back

[![Image 1: C++ Container Class ](#) C++ Container Class ](#) * * * Among all containers, `vector` is the most commonly used and most similar to an automatically resizable array, and `push_back` is the key function that makes this array grow. `push_back` is a member function used to add a new element to the **end** of a **dynamic array (`vector`)** or **other sequence containers (such as `list`, `deque`)**. `push_back` implements **dynamic growth** of the container. You don't need to specify the final size of the container in advance; you can add elements anytime, anywhere based on the needs of your program at runtime. **Word meaning**: `push` means to push in, `back` means the rear, combined it means pushing to the backβ€”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 call it through the dot operator `.`. ### Syntax Format void push_back(const T& value);void push_back(T&& value); // C++11 and later (supports rvalue) ### Parameter Description * **Parameter**: `value` * Type: Consistent with the element type specified when defining the container, or a value that can be converted to that type. * Description: The value you want to add to the end of the container. Can be a variable, a literal (such as `10`, `"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**: The container's `size()` (current number of elements) increases by 1. The new element becomes the last element of the container. * * * ## Examples Let's thoroughly master the usage of `push_back` through a series of examples from simple to complex. ### Example 1: Basic Usage - Managing Integers ## Example #include #include // 1. Must include vector header file int main(){ // 2. Create an empty vector to store integers std::vector numbers; std::cout<<"Initial vector size: "<< 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, vector size: "<< numbers.size()<< std::endl; // 4. Traverse and output all elements to verify the addition order std::cout<<"Elements in vector: "; for(int i =0; i < numbers.size();++i){ std::cout<< numbers<<" ";// Access via index like an array } std::cout<< std::endl; return 0; } **Expected Output:** Initial vector size: 0After adding, vector size: 3 Elements in vector: 10 20 30 **Code Analysis:** 1. `#include ` is a prerequisite for using the `vector` container. 2. `std::vector numbers;` creates an empty `vector` named `numbers` that will store `int` type integers. 3. Three `push_back` calls sequentially add `10`, `20`, `30` to the end of `numbers`. The order of addition is the final order of elements in the `vector`. 4. `numbers.size()` returns the current number of elements. `numbers` 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 types. ## Example #include #include #include // Need to include header file for string int main(){ // Create a vector that stores std::string std::vector 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 list ("<< tasks.size()<<" items):n"; // Use range-based for loop (C++11) to traverse, more concise for(const auto& task : tasks){ std::cout<<"- "<< task << std::endl; } return 0; } **Expected Output:** Today's to-do list (3 items):- Learn C++ push_back - Do homework- Read technical documentation **Code Analysis:** * `std::vector` declares a container with element type `std::string`. * The parameter of `push_back` is now a string literal (will be automatically converted to `std::string`). * `for(const auto& task : tasks)` is the "range-based for loop" introduced in C++11, which automatically traverses every element in `tasks`, very convenient. `auto` lets the compiler automatically deduce the type of `task`. ### Example 3: Dynamically Building Container Content This is where `push_back` is most powerful: building containers based on runtime data (such as user input, file reading). ## Example #include #include int main(){ std::vector scores; int inputScore; char continueFlag ='y'; std::cout<> inputScore){ scores.push_back(inputScore); } // Clear cin 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 <> inputScore; scores.push_back(inputScore); std::cout <> continueFlag; } */ std::cout<<"n Total of "<< scores.size()<<" scores entered.n"; if(!scores.empty()){// Check if container is empty int sum =0; for(int score : scores){ sum += score; } std::cout<<"Average score: "<<static_cast(sum)/ scores.size()<< std::endl; } return 0; } This example demonstrates how to use `push_back` to dynamically fill a container in a loop and finally calculate the average. You can try running it and entering `100 90 85 a` (entering a letter `a` at the end to end the numeric input loop). * * C++ Container Class ](#)
← Cpp Libs Vector AtLanggraph Quick Start β†’