push_back


keyword: push_back in STL containers

push_back is a member function available in several STL (Standard Template Library) containers in C++. It's primarily used to add elements to the end of a container. This method is most commonly associated with std::vector, but it's also available in other sequence containers like std::deque and std::list.

Key Characteristics

Example 1: Basic Usage with std::vector

#include <iostream>
#include <vector>

int main() {
    std::vector<int> numbers;

    // Adding elements using push_back
    numbers.push_back(10);
    numbers.push_back(20);
    numbers.push_back(30);

    // Printing the vector
    std::cout << "Vector contents: ";
    for (int num : numbers) {
        std::cout << num << " ";
    }
    std::cout << std::endl;

    // Checking size
    std::cout << "Vector size: " << numbers.size() << std::endl;

    return 0;
}

Explanation:

Example 2: Using push_back with Custom Objects

#include <iostream>
#include <vector>
#include <string>

class Person {
private:
    std::string name;
    int age;

public:
    Person(const std::string& n, int a) : name(n), age(a) {}

    void display() const {
        std::cout << name << " (" << age << " years old)" << std::endl;
    }
};

int main() {
    std::vector<Person> people;

    // Adding Person objects to the vector
    people.push_back(Person("Alice", 30));
    people.push_back(Person("Bob", 25));
    people.emplace_back("Charlie", 35);  // Using emplace_back for in-place construction

    // Displaying all persons
    std::cout << "People in the vector:" << std::endl;
    for (const auto& person : people) {
        person.display();
    }

    return 0;
}

Explanation:

Example 3: push_back with std::deque

#include <iostream>
#include <deque>
#include <string>

int main() {
    std::deque<std::string> colors;

    // Adding elements to the back
    colors.push_back("Red");
    colors.push_back("Green");
    colors.push_back("Blue");

    // Adding an element to the front (for comparison)
    colors.push_front("Yellow");

    // Printing the deque
    std::cout << "Colors in the deque:" << std::endl;
    for (const auto& color : colors) {
        std::cout << color << " ";
    }
    std::cout << std::endl;

    return 0;
}

Explanation:

Example 4: Performance Considerations with std::vector

#include <iostream>
#include <vector>
#include <chrono>

int main() {
    const int NUM_ELEMENTS = 1000000;
    std::vector<int> vec;

    // Reserve space to avoid reallocations
    vec.reserve(NUM_ELEMENTS);

    auto start = std::chrono::high_resolution_clock::now();

    for (int i = 0; i < NUM_ELEMENTS; ++i) {
        vec.push_back(i);
    }

    auto end = std::chrono::high_resolution_clock::now();
    std::chrono::duration<double> diff = end - start;

    std::cout << "Time to add " << NUM_ELEMENTS << " elements: " 
              << diff.count() << " seconds" << std::endl;
    std::cout << "Final vector size: " << vec.size() << std::endl;

    return 0;
}

Explanation:

Additional Considerations

  1. Reallocation: For vector, push_back may cause reallocation if the capacity is exceeded, which can be expensive.

  2. Exception Safety: push_back provides a strong exception guarantee. If an exception is thrown, the container remains unchanged.

  3. Efficiency: For vector, using reserve before multiple push_back calls can improve performance by reducing reallocations.

  4. Alternatives: Consider using emplace_back for in-place construction of elements, which can be more efficient for complex objects.

  5. Iterator Invalidation: For vector, push_back may invalidate iterators and references if reallocation occurs.

Summary

push_back is a fundamental method for adding elements to the end of STL containers:

  1. It's primarily used with vector, deque, and list.
  2. Adds an element to the end of the container, increasing its size.
  3. Has constant time complexity for deque and list, and amortized constant time for vector.
  4. May cause reallocation in vector if capacity is exceeded.

Key points to remember: - Simple and intuitive way to add elements to a container. - Performance can be optimized in vector by using reserve. - Provides strong exception guarantee. - Available in multiple sequence containers but not in associative containers.

Best practices: - Use reserve with vector when the number of elements is known beforehand. - Consider emplace_back for constructing objects in-place. - Be aware of potential iterator invalidation, especially with vector. - Use push_back for its simplicity when adding elements one at a time.

push_back is a versatile and widely-used method in C++ STL, essential for dynamic container management and a key tool in many C++ programming scenarios.

Related

Previous Page | Course Schedule | Course Content