Cheat Sheet
- Linux: /linux/
- CLI: /linux/cli/
- locate vs type vs which vs whereis: /linux/cli/locate-vs-type-vs-which-vs-whereis/
- make: /linux/cli/make/
- awk: /linux/cli/awk/
- find: /linux/cli/find/
- grep: /linux/cli/grep/
- pgrep: /linux/cli/pgrep/
- ps: /linux/cli/ps/
- pstree: /linux/cli/pstree/
- trap: /linux/cli/trap/
- xargs: /linux/cli/xargs/
- Shell: /linux/shell/
- BASH_SOURCE: /linux/shell/bash-source/
- Redirection: /linux/shell/redirection/
- Special Variables: /linux/shell/special-variables/
- Scripting Tips: /linux/shell/script-tips/
- set -o vi: /linux/shell/bash-vi-mode/
- Shell Processing Order: /linux/shell/process-order/
- What are Interactive and Login Shells?: /linux/shell/interactive-login/
- Double Quote Expansion: /linux/shell/shell-expansion/
- System Programming: /linux/system-programming/
- File I/O: /linux/system-programming/file-io/
- Process: /linux/system-programming/process/
- Shared Libraries: /linux/system-programming/shared-libraries/
- Kernel: /linux/kernel/
- Go: /programming/go/
- Concurrency: /programming/go/concurrency/
- CSP (Communicating Sequential Processes) and Channels: /programming/go/concurrency/csp/
- Channel: /programming/go/concurrency/channel/
- Select: /programming/go/concurrency/select/
- sync: /programming/go/concurrency/sync/
- Concurrency Patterns: /programming/go/concurrency/patterns/
- Goroutines and the Go Runtime: /programming/go/concurrency/runtime/
- Standard Library: /programming/go/std/
- os: /programming/go/std/os/
- context: /programming/go/std/context/
- io: /programming/go/std/io/
- json: /programming/go/std/json/
- net/http: /programming/go/std/net-http/
- slog: /programming/go/std/slog/
- testing: /programming/go/std/testing/
- time: /programming/go/std/time/
- Ellipsis (...): /programming/go/ellipsis/
- error: /programming/go/error/
- Function: /programming/go/function/
- Go Tool: /programming/go/tool/
- Interface: /programming/go/interface/
- Map: /programming/go/map/
- Package and Module: /programming/go/package-module/
- Pointer: /programming/go/pointer/
- Slice: /programming/go/slice/
- String: /programming/go/string/
- Switch: /programming/go/switch/
- Comparison: /programming/go/comparison/
- defaultdict: /programming/python/collections/defaultdict/
- heapq: /programming/python/collections/heapq/
- @cache: /programming/python/cache/
- abc: /programming/python/abc/
- bisect: /programming/python/bisect/
- Type Hints: /programming/python/type-hints/
- Passing Mechanism: /programming/python/passing-mechanism/
- uv: /programming/python/uv/
- *args and **kwargs: /programming/python/args-kwargs/
- re: /programming/python/re/
- C: /programming/c/
- Pointers and Arrays: /programming/c/pointer/
- Syntax Basics: /programming/c/syntax-basics/
- static: /programming/c/static/
- Bit Manipulation: /programming/c/bit-manipulation/
- C vs C++: /programming/c/c-vs-cpp/
- stdatomic: /programming/c/stdatomic/
- C++: /programming/cpp/
- RAII (Resource Acquisition Is Initialization): /programming/cpp/raii/
- Copy Elision & Move Semantics: /programming/cpp/copy-elision-and-move-semantics/
- Most Vexing Parse & In-Class Initializer: /programming/cpp/most-vexing-parse/
- C++ Keywords Reference: /programming/cpp/keywords/
- C++ Primer: /programming/cpp/primer/
- Variables and Basic Types: /programming/cpp/primer/variables-and-basic-types/
- Expressions: /programming/cpp/primer/expressions/
- Type Conversions and Casts: /programming/cpp/primer/type-conversions-and-casts/
- Statements: /programming/cpp/primer/statements/
- Functions: /programming/cpp/primer/functions/
- Classes: /programming/cpp/primer/classes/
- The IO Library: /programming/cpp/primer/io-library/
- STL: /programming/cpp/primer/stl/
- Lambda Expressions: /programming/cpp/primer/lambda/
- Smart Pointers: /programming/cpp/primer/smart-pointers/
- Copy Control: /programming/cpp/primer/copy-control/
- Overloaded Operations and Conversions: /programming/cpp/primer/operator-overloading/
- Object-Oriented Programming (OOP): /programming/cpp/primer/oop/
- Templates and Generic Programming: /programming/cpp/primer/templates/
- Namespaces: /programming/cpp/primer/namespaces/
- Pointers to Class Member: /programming/cpp/primer/pointers-to-class-member/
- Advanced: /programming/cpp/advanced/
- Error Handling: /programming/cpp/advanced/error-handling/
- Concurrency & Threading: /programming/cpp/advanced/concurrency/
- Unit Testing: /programming/cpp/advanced/unit-testing/
- Comparison: /programming/comparison/
- Kubernetes: /cloud-devops/kubernetes/
- Fleet: /cloud-devops/kubernetes/gke/fleet/
- Kustomize vs Helm: /cloud-devops/kubernetes/kustomize-vs-helm/
- API Extension: /cloud-devops/kubernetes/api-extension/
- Concept: /cloud-devops/kubernetes/kueue/concept/
- DRA: /cloud-devops/kubernetes/dra/
- Secret Manager: /cloud-devops/terraform/google-secret-manager/
- Knowledge: /network/knowledge/
- PDU: /network/knowledge/osi-model/
- curl: /network/cli/curl/
- Concurrency Concepts: /cs/concurrency-and-parallelism/concepts/
- Concurrency vs Parallelism: /cs/concurrency-and-parallelism/concurrency-vs-parallelism/
- Mutex vs Atomic: /cs/concurrency-and-parallelism/mutex-vs-atomic/
- Regular Expression: /cs/regular-expression/
- Multiplexer vs Dispatcher: /cs/multiplexer-vs-dispatcher/
- Driver and Runtime: /ai-ml/gpu/driver-and-runtime/
- Serving: /ai-ml/serving/
- Dotfiles: /dotfiles/
- Git: /dotfiles/git/
- Cheat Sheet: /dotfiles/git/cheat-sheet/
- revisions: /dotfiles/git/revisions/
- Submodule vs Worktree: /dotfiles/git/submodule-vs-worktree/
- checkout, reset -> switch, restore: /dotfiles/git/checkout-switch-restore-reset/
- rebase: /dotfiles/git/rebase/
- Branching and Merging: /dotfiles/git/branching-merging/
- Vim: /dotfiles/vim/
- Plugin: /dotfiles/vim/plugin/
- auto-pairs: /dotfiles/vim/plugin/auto-pairs/
- vim-commentary: /dotfiles/vim/plugin/vim-commentary/
- vim-easymotion: /dotfiles/vim/plugin/vim-easymotion/
- vim-surround: /dotfiles/vim/plugin/vim-surround/
- Marks: /dotfiles/vim/tips/marks/
- vimrc: /dotfiles/vim/vimrc/
- lf: /dotfiles/lf/
# 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()`).
```cpp
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.
```cpp
for (auto it = v.cend(); it != v.cbegin(); ) {
--it;
/* process *it */
}
```
> **Note:** Dedicated reverse iterators (`rbegin()` / `rend()`) advance backward using `++rit`:
> ```cpp
> 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.
```cpp
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.
```cpp
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 site
2. 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)...`) (see [Templates]({{< relref "/programming/cpp/primer/templates.md" >}})) |
### 2. Code Comparison
```cpp
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 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_back` is better:** Use `emplace_back` when **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_back` is equal or better:**
- When **inserting an already-existing object (lvalue) or an already-constructed temporary** (`c.push_back(item)` or `c.push_back(std::move(item))`), `emplace_back` still invokes the copy or move constructor anyway, offering zero performance benefit.
- Because `emplace_back` can directly invoke `explicit` constructors, 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.
- Therefore, **use `emplace_back` only when constructing in-place from constructor arguments, and prefer `push_back` when inserting an existing value**.