STL#
Summary of core iterator traversal and erase patterns and element insertion (push_back vs emplace_back) from C++ Primer, 5th ed. Chapter 9 (Sequential Containers).
1. Iterator Traversal & Erase Patterns#
1. Forward Traversal#
When elements do not need to be modified, prefer constant iterators (cbegin() / cend()).
for (auto it = v.cbegin(); it != v.cend(); ++it) {
/* process *it */
}2. Reverse Traversal with Bidirectional Iterators#
Because cend() points one past the last element rather than to the last element itself, decrement --it at the very beginning of the loop body right after the condition check.
for (auto it = v.cend(); it != v.cbegin(); ) {
--it;
/* process *it */
}Note: Dedicated reverse iterators (
rbegin()/rend()) advance backward using++rit:for (auto rit = v.crbegin(); rit != v.crend(); ++rit) { /* process *rit */ }
3. Forward Traversal with Erase#
Calling v.erase(it) immediately invalidates the erased iterator it, so executing ++it afterward causes undefined behavior (UB).
Because erase(it) returns a valid iterator pointing to the element immediately following the erased one, update it with the return value when erasing, and only increment ++it in the else branch.
for (auto it = v.begin(); it != v.end(); ) {
if (condition_to_erase) {
it = v.erase(it); // Advance 'it' to the valid iterator returned by erase()
} else {
++it;
}
}4. Reverse Traversal with Erase#
After stepping backward (--it), calling it = v.erase(it) returns a valid iterator to the element that shifted into the erased position (i.e., immediately after the element just inspected). On the next iteration, --it at the top of the loop safely moves to the preceding element.
for (auto it = v.end(); it != v.begin(); ) {
--it;
if (condition_to_erase) {
it = v.erase(it);
}
}2. push_back vs emplace_back#
Introduced in C++11, emplace operations (emplace_back, emplace_front, emplace) differ from push/insert in that rather than copying or moving an existing object into the container, they accept constructor arguments for the element type and construct the object directly in-place within the container’s managed memory.
1. Core Behavioral Differences#
| Category | push_back (push_front, insert) | emplace_back (emplace_front, emplace) |
|---|---|---|
| Arguments Passed | A constructed T object (const T& or T&&) | Constructor arguments for T |
| Execution Steps (When Creating a New Element) | 1. Construct a temporary T object at the call site2. Invoke move (or copy) constructor into container memory 3. Invoke destructor on the temporary object at ; | Invoke T(ARGS...) constructor only once directly inside the container’s memory space (no temporary creation, move, or destruction) |
explicit Constructors | Implicit conversion is disallowed → must explicitly construct a temporary such as v.push_back(T(ARG)) | Directly invokes the constructor inside the container, so explicit constructors can be called via v.emplace_back(ARG) |
| Internal Mechanism | Function overloading: push_back(const T&) and push_back(T&&) | Variadic templates (ARGS&&...) + Perfect Forwarding (std::forward<ARGS>(args)...) (see Templates) |
2. Code Comparison#
struct Sales_data {
std::string bookNo;
unsigned units_sold = 0;
double revenue = 0.0;
Sales_data(const std::string &s, unsigned n, double p)
: bookNo(s), units_sold(n), revenue(n * p) {}
explicit Sales_data(const std::string &s) : bookNo(s) {}
};
std::vector<Sales_data> c;
// 1. emplace_back: Pass 3 constructor arguments for Sales_data directly
// -> Constructs Sales_data("978-0", 25, 15.99) in-place inside vector memory with no temporary!
c.emplace_back("978-0", 25, 15.99);
// 2. push_back: Passing 3 constructor arguments directly is a compile error!
// c.push_back("978-0", 25, 15.99); // Error: no overload of push_back takes 3 arguments
// -> Creates a temporary Sales_data object first, moves it into the vector, then destroys the temporary
c.push_back(Sales_data("978-0", 25, 15.99));3. When to Use Which?#
- When
emplace_backis better: Useemplace_backwhen constructing a brand-new element inside the container by passing constructor arguments. It completely eliminates the creation, move/copy, and destruction of a temporary object. - When
push_backis equal or better:- When inserting an already-existing object (lvalue) or an already-constructed temporary (
c.push_back(item)orc.push_back(std::move(item))),emplace_backstill invokes the copy or move constructor anyway, offering zero performance benefit. - Because
emplace_backcan directly invokeexplicitconstructors, passing the wrong argument type by mistake (e.g., passing a raw pointer or integer to a container of smart pointers or vectors) can trigger unintended construction.
- When inserting an already-existing object (lvalue) or an already-constructed temporary (
- Therefore, use
emplace_backonly when constructing in-place from constructor arguments, and preferpush_backwhen inserting an existing value.