Skip to content

C++98 STL Concepts ​

This document covers C++98 Standard Template Library (STL) concepts with simple explanations, real-world scenarios, and short code snippets. Full examples will be added in examples folder.

Containers ​

std::vector ​

Explanation: Dynamic array that grows or shrinks as needed.

Real-World Scenario: Store a list of user messages in a chat application.

Snippet:

cpp
#include <vector> std::vector<int> vec = {1, 2, 3};

Example: vector.cpp

std::list ​

Explanation: Doubly-linked list for efficient insertions and deletions.

Real-World Scenario: Manage a playlist with frequent song reordering.

Snippet:

cpp
#include <list> std::list<int> lst = {1, 2, 3};

Example: list.cpp

std::deque ​

Explanation: Double-ended queue supporting fast insertions at both ends.

Real-World Scenario: Implement a task queue in a job scheduler.

Snippet:

cpp
#include <deque> std::deque<int> dq = {1, 2, 3};

Example: deque.cpp

std::set ​

Explanation: Sorted collection of unique elements.

Real-World Scenario: Store unique user IDs in a membership system.

Snippet:

cpp
#include <set> std::set<int> s = {1, 2, 3};

Example: set.cpp

std::map ​

Explanation: Sorted key-value pairs with unique keys.

Real-World Scenario: Store student grades by ID in a school database.

Snippet:

cpp
#include <map> std::map<int, string> m = {{1, "A"}};

Example: map.cpp

std::multiset ​

Explanation: Sorted collection allowing duplicate elements.

Real-World Scenario: Track multiple event timestamps in a log.

Snippet:

cpp
#include <multiset> std::multiset<int> ms = {1, 1, 2};

Example: multiset.cpp

std::multimap ​

Explanation: Sorted key-value pairs allowing duplicate keys.

Real-World Scenario: Store multiple phone numbers per contact in an address book.

Snippet:

cpp
#include <map> std::multimap<int, string> mm = {{1, "A"}};

Example: multimap.cpp

std::stack (Container Adaptor) ​

Explanation: LIFO (last-in, first-out) container adaptor.

Real-World Scenario: Implement undo functionality in a text editor.

Snippet:

cpp
#include <stack> std::stack<int> stk; stk.push(1);

Example: stack.cpp

std::queue (Container Adaptor) ​

Explanation: FIFO (first-in, first-out) container adaptor.

Real-World Scenario: Manage print jobs in a printer queue.

Snippet:

cpp
#include <queue> std::queue<int> q; q.push(1);

Example: queue.cpp

std::priority_queue (Container Adaptor) ​

Explanation: Queue where the largest element is always at the top.

Real-World Scenario: Schedule tasks by priority in a task manager.

Snippet:

cpp
#include <queue> std::priority_queue<int> pq; pq.push(1);

Example: priority_queue.cpp

std::bitset ​

Explanation: A fixed-size sequence of bits with efficient bitwise operations and conversions.

Real-World Scenario: Represent and manipulate feature flags or permissions in a role-based access system.

Snippet:

cpp
#include <bitset>
std::bitset<8> flags("10110010");
bool isSet = flags.test(4);

Example: bitset.cpp

Iterators ​

Input Iterator ​

Explanation: Reads elements in a sequence (single-pass, read-only).

Real-World Scenario: Read data from a file stream in a data parser.

Snippet:

cpp
std::istream_iterator<int> it(std::cin);

Example: input_iterator.cpp

Output Iterator ​

Explanation: Writes elements to a sequence (single-pass, write-only).

Real-World Scenario: Write results to an output stream in a logging system.

Snippet:

cpp
std::ostream_iterator<int> it(std::cout, " ");

Example: output_iterator.cpp

Forward Iterator ​

Explanation: Reads/writes elements, supports multiple passes in one direction.

Real-World Scenario: Traverse a linked list in a navigation system.

Snippet:

cpp
std::list<int>::iterator it = lst.begin();

Example: forward_iterator.cpp

Bidirectional Iterator ​

Explanation: Reads/writes elements, moves forward and backward.

Real-World Scenario: Navigate a playlist forward and backward.

Snippet:

cpp
std::list<int>::iterator it = lst.begin(); ++it; --it;

Example: bidirectional_iterator.cpp

Random Access Iterator ​

Explanation: Reads/writes elements with direct access via indexing.

Real-World Scenario: Access elements in an array-based database randomly.

Snippet:

cpp
std::vector<int>::iterator it = vec.begin(); it += 2;

Example: random_access_iterator.cpp

Iterator Traits ​

Explanation: Provides metadata about iterator types (e.g., value_type).

Real-World Scenario: Write generic algorithms that adapt to iterator types.

Snippet:

cpp
std::iterator_traits<It>::value_type val;

Example: iterator_traits.cpp

std::iterator ​

Explanation: Base class for defining custom iterators.

Real-World Scenario: Create a custom iterator for a user-defined container.

Snippet:

cpp
#include <iterator> class MyIterator : public std::iterator<std::forward_iterator_tag, int> {};

Example: iterator.cpp

std::advance ​

Explanation: Moves an iterator by a specified distance.

Real-World Scenario: Skip elements in a list during data processing.

Snippet:

cpp
std::list<int>::iterator it = lst.begin(); std::advance(it, 2);

Example: advance.cpp

std::distance ​

Explanation: Calculates the number of elements between two iterators.

Real-World Scenario: Determine the size of a range in a search algorithm.

Snippet:

cpp
std::distance(vec.begin(), vec.end());

Example: distance.cpp

std::next ​

Explanation: Returns an iterator advanced by a given distance.

Real-World Scenario: Get the next element in a sequence for processing.

Snippet:

cpp
std::list<int>::iterator it = std::next(lst.begin());

Example: next.cpp

std::prev ​

Explanation: Returns an iterator moved backward by a given distance.

Real-World Scenario: Access the previous element in a playlist.

Snippet:

cpp
std::list<int>::iterator it = std::prev(lst.end());

Example: prev.cpp

Iterator Adaptors ​

std::reverse_iterator ​

Explanation: Traverses a sequence in reverse order.

Real-World Scenario: Print events in reverse chronological order.

Snippet:

cpp
std::vector<int>::reverse_iterator rit = vec.rbegin();

Example: reverse_iterator.cpp

std::back_insert_iterator ​

Explanation: Inserts elements at the end of a container.

Real-World Scenario: Append data to a vector in a data collection system.

Snippet:

cpp
std::back_insert_iterator<std::vector<int>> it(vec);

Example: back_insert_iterator.cpp

std::front_insert_iterator ​

Explanation: Inserts elements at the beginning of a container.

Real-World Scenario: Add tasks to the front of a deque in a scheduler.

Snippet:

cpp
std::front_insert_iterator<std::deque<int>> it(dq);

Example: front_insert_iterator.cpp

std::insert_iterator ​

Explanation: Inserts elements at a specific position in a container.

Real-World Scenario: Insert data into a set during a merge operation.

Snippet:

cpp
std::insert_iterator<std::set<int>> it(s);

Example: insert_iterator.cpp

std::istream_iterator ​

Explanation: Reads elements from an input stream as an iterator.

Real-World Scenario: Read numbers from a file in a data parser.

Snippet:

cpp
std::istream_iterator<int> it(std::cin);

Example: istream_iterator.cpp

std::ostream_iterator ​

Explanation: Writes elements to an output stream as an iterator.

Real-World Scenario: Write results to a file in a logging system.

Snippet:

cpp
std::ostream_iterator<int> it(std::cout, " ");

Example: ostream_iterator.cpp

std::istreambuf_iterator ​

Explanation: Reads characters directly from an input stream buffer.

Real-World Scenario: Process raw input in a text parser.

Snippet:

cpp
std::istreambuf_iterator<char> it(std::cin);

Example: istreambuf_iterator.cpp

std::ostreambuf_iterator ​

Explanation: Writes characters directly to an output stream buffer.

Real-World Scenario: Write raw data to a file in a logging system.

Snippet:

cpp
std::ostreambuf_iterator<char> it(std::cout);

Example: ostreambuf_iterator.cpp

Algorithms ​

std::for_each ​

Explanation: Applies a function to each element in a range.

Real-World Scenario: Print all items in a shopping cart.

Snippet:

cpp
std::for_each(vec.begin(), vec.end(), print);

Example: for_each.cpp

std::find ​

Explanation: Finds the first occurrence of a value in a range.

Real-World Scenario: Locate a user ID in a database.

Snippet:

cpp
std::find(vec.begin(), vec.end(), 5);

Example: find.cpp

std::find_if ​

Explanation: Finds the first element satisfying a predicate.

Real-World Scenario: Find the first overdue task in a scheduler.

Snippet:

cpp
std::find_if(vec.begin(), vec.end(), isEven);

Example: find_if.cpp

std::find_end ​

Explanation: Finds the last occurrence of a subsequence in a range.

Real-World Scenario: Locate the last matching pattern in a text search.

Snippet:

cpp
std::find_end(vec.begin(), vec.end(), sub.begin(), sub.end());

Example: find_end.cpp

std::find_first_of ​

Explanation: Finds the first element matching any from another range.

Real-World Scenario: Find a special character in a string parser.

Snippet:

cpp
std::find_first_of(vec.begin(), vec.end(), chars.begin(), chars.end());

Example: find_first_of.cpp

std::adjacent_find ​

Explanation: Finds the first pair of adjacent equal elements.

Real-World Scenario: Detect consecutive duplicate entries in a log.

Snippet:

cpp
std::adjacent_find(vec.begin(), vec.end());

Example: adjacent_find.cpp

std::count ​

Explanation: Counts occurrences of a value in a range.

Real-World Scenario: Count product appearances in a cart.

Snippet:

cpp
std::count(vec.begin(), vec.end(), 5);

Example: count.cpp

std::count_if ​

Explanation: Counts elements satisfying a predicate.

Real-World Scenario: Count completed tasks in a to-do list.

Snippet:

cpp
std::count_if(vec.begin(), vec.end(), isPositive);

Example: count_if.cpp

std::mismatch ​

Explanation: Finds the first position where two ranges differ.

Real-World Scenario: Compare two file versions for differences.

Snippet:

cpp
std::mismatch(vec1.begin(), vec1.end(), vec2.begin());

Example: mismatch.cpp

std::equal ​

Explanation: Checks if two ranges are equal.

Real-World Scenario: Verify identical settings in two user profiles.

Snippet:

cpp
std::equal(vec1.begin(), vec1.end(), vec2.begin());

Example: equal.cpp

std::search ​

Explanation: Finds the first occurrence of a subsequence in a range.

Real-World Scenario: Search for a pattern in a text editor.

Snippet:

cpp
std::search(vec.begin(), vec.end(), sub.begin(), sub.end());

Example: search.cpp

std::search_n ​

Explanation: Finds n consecutive equal elements.

Real-World Scenario: Detect repeated characters in a password validator.

Snippet:

cpp
std::search_n(vec.begin(), vec.end(), 2, 5);

Example: search_n.cpp

std::copy ​

Explanation: Copies elements from one range to another.

Real-World Scenario: Duplicate a list of items in a backup system.

Snippet:

cpp
std::copy(vec.begin(), vec.end(), dest.begin());

Example: copy.cpp

std::copy_backward ​

Explanation: Copies elements in reverse order to a destination.

Real-World Scenario: Reverse-copy a log for display in a UI.

Snippet:

cpp
std::copy_backward(vec.begin(), vec.end(), dest.end());

Example: copy_backward.cpp

std::move (Algorithm) ​

Explanation: Moves elements from one range to another (not move semantics).

Real-World Scenario: Transfer data between buffers in a network app.

Snippet:

cpp
std::move(vec.begin(), vec.end(), dest.begin());

Example: move_algorithm.cpp

std::move_backward ​

Explanation: Moves elements in reverse order to a destination.

Real-World Scenario: Reverse-move data in a memory management system.

Snippet:

cpp
std::move_backward(vec.begin(), vec.end(), dest.end());

Example: move_backward.cpp

std::fill ​

Explanation: Fills a range with a specified value.

Real-World Scenario: Initialize an array of scores to zero in a game.

Snippet:

cpp
std::fill(vec.begin(), vec.end(), 0);

Example: fill.cpp

std::fill_n ​

Explanation: Fills n elements with a specified value.

Real-World Scenario: Set the first n slots of a buffer to a default value.

Snippet:

cpp
std::fill_n(vec.begin(), 5, 0);

Example: fill_n.cpp

std::transform ​

Explanation: Applies a function to a range, storing results elsewhere.

Real-World Scenario: Convert temperatures from Celsius to Fahrenheit.

Snippet:

cpp
std::transform(vec.begin(), vec.end(), dest.begin(), toFahrenheit);

Example: transform.cpp

std::generate ​

Explanation: Assigns values from a generator function to a range.

Real-World Scenario: Generate random IDs for users in a registration system.

Snippet:

cpp
std::generate(vec.begin(), vec.end(), rand);

Example: generate.cpp

std::generate_n ​

Explanation: Assigns values from a generator to n elements.

Real-World Scenario: Generate n unique IDs for a batch process.

Snippet:

cpp
std::generate_n(vec.begin(), 5, rand);

Example: generate_n.cpp

std::remove ​

Explanation: Moves elements not matching a value to the front of a range.

Real-World Scenario: Remove invalid entries from a dataset.

Snippet:

cpp
std::remove(vec.begin(), vec.end(), 0);

Example: remove.cpp

std::remove_if ​

Explanation: Moves elements not satisfying a predicate to the front.

Real-World Scenario: Remove negative values from a financial report.

Snippet:

cpp
std::remove_if(vec.begin(), vec.end(), isNegative);

Example: remove_if.cpp

std::replace ​

Explanation: Replaces all occurrences of a value in a range.

Real-World Scenario: Replace placeholder text in a template engine.

Snippet:

cpp
std::replace(vec.begin(), vec.end(), 0, 1);

Example: replace.cpp

std::replace_if ​

Explanation: Replaces elements satisfying a predicate.

Real-World Scenario: Replace negative scores with zero in a game.

Snippet:

cpp
std::replace_if(vec.begin(), vec.end(), isNegative, 0);

Example: replace_if.cpp

std::swap ​

Explanation: Exchanges values of two variables.

Real-World Scenario: Swap two elements in a sorting algorithm.

Snippet:

cpp
std::swap(x, y);

Example: swap.cpp

std::swap_ranges ​

Explanation: Exchanges elements between two ranges.

Real-World Scenario: Swap two rows in a matrix editor.

Snippet:

cpp
std::swap_ranges(vec1.begin(), vec1.end(), vec2.begin());

Example: swap_ranges.cpp

std::iter_swap ​

Explanation: Swaps elements pointed to by two iterators.

Real-World Scenario: Swap two items in a playlist reorder operation.

Snippet:

cpp
std::iter_swap(vec.begin(), vec.begin() + 1);

Example: iter_swap.cpp

std::reverse ​

Explanation: Reverses the order of elements in a range.

Real-World Scenario: Reverse a list of events for chronological display.

Snippet:

cpp
std::reverse(vec.begin(), vec.end());

Example: reverse.cpp

std::reverse_copy ​

Explanation: Copies a range in reverse order to a destination.

Real-World Scenario: Create a reversed copy of a log for analysis.

Snippet:

cpp
std::reverse_copy(vec.begin(), vec.end(), dest.begin());

Example: reverse_copy.cpp

std::rotate ​

Explanation: Rotates elements in a range around a pivot.

Real-World Scenario: Shift elements in a circular buffer.

Snippet:

cpp
std::rotate(vec.begin(), vec.begin() + 2, vec.end());

Example: rotate.cpp

std::rotate_copy ​

Explanation: Copies a rotated range to a destination.

Real-World Scenario: Create a rotated version of a schedule for display.

Snippet:

cpp
std::rotate_copy(vec.begin(), vec.begin() + 2, vec.end(), dest.begin());

Example: rotate_copy.cpp

std::unique ​

Explanation: Removes consecutive duplicates in a range.

Real-World Scenario: Clean up duplicate entries in a log file.

Snippet:

cpp
std::unique(vec.begin(), vec.end());

Example: unique.cpp

std::unique_copy ​

Explanation: Copies a range, removing consecutive duplicates.

Real-World Scenario: Create a deduplicated list of user inputs.

Snippet:

cpp
std::unique_copy(vec.begin(), vec.end(), dest.begin());

Example: unique_copy.cpp

std::partition ​

Explanation: Reorders elements so those satisfying a predicate come first.

Real-World Scenario: Separate completed tasks in a to-do list.

Snippet:

cpp
std::partition(vec.begin(), vec.end(), isPositive);

Example: partition.cpp

std::stable_partition ​

Explanation: Partitions while preserving relative order.

Real-World Scenario: Group items by category while maintaining order in a catalog.

Snippet:

cpp
std::stable_partition(vec.begin(), vec.end(), isPositive);

Example: stable_partition.cpp

std::sort ​

Explanation: Sorts elements in a range.

Real-World Scenario: Sort a leaderboard by scores in a game.

Snippet:

cpp
std::sort(vec.begin(), vec.end());

Example: sort.cpp

std::stable_sort ​

Explanation: Sorts while preserving relative order of equal elements.

Real-World Scenario: Sort products by price, keeping same-priced items in order.

Snippet:

cpp
std::stable_sort(vec.begin(), vec.end());

Example: stable_sort.cpp

std::partial_sort ​

Explanation: Sorts the first n elements of a range.

Real-World Scenario: Display the top 5 scores in a leaderboard.

Snippet:

cpp
std::partial_sort(vec.begin(), vec.begin() + 5, vec.end());

Example: partial_sort.cpp

std::partial_sort_copy ​

Explanation: Copies the smallest n elements in sorted order.

Real-World Scenario: Copy top items to a summary report.

Snippet:

cpp
std::partial_sort_copy(vec.begin(), vec.end(), dest.begin(), dest.end());

Example: partial_sort_copy.cpp

std::nth_element ​

Explanation: Places the nth element in its sorted position.

Real-World Scenario: Find the median value in a dataset.

Snippet:

cpp
std::nth_element(vec.begin(), vec.begin() + n, vec.end());

Example: nth_element.cpp

std::merge ​

Explanation: Merges two sorted ranges into a destination.

Real-World Scenario: Combine two sorted lists of orders in an e-commerce system.

Snippet:

cpp
std::merge(vec1.begin(), vec1.end(), vec2.begin(), vec2.end(), dest.begin());

Example: merge.cpp

std::inplace_merge ​

Explanation: Merges two sorted subranges in place.

Real-World Scenario: Merge sorted halves of a dataset in a database.

Snippet:

cpp
std::inplace_merge(vec.begin(), vec.begin() + n, vec.end());

Example: inplace_merge.cpp

std::includes ​

Explanation: Checks if one sorted range is a subset of another.

Real-World Scenario: Verify if a user’s permissions include required ones.

Snippet:

cpp
std::includes(vec1.begin(), vec1.end(), vec2.begin(), vec2.end());

Example: includes.cpp

std::set_union ​

Explanation: Combines two sorted ranges, keeping unique elements.

Real-World Scenario: Merge two lists of unique users from different sources.

Snippet:

cpp
std::set_union(vec1.begin(), vec1.end(), vec2.begin(), vec2.end(), dest.begin());

Example: set_union.cpp

std::set_intersection ​

Explanation: Finds elements common to two sorted ranges.

Real-World Scenario: Identify common items in two inventories.

Snippet:

cpp
std::set_intersection(vec1.begin(), vec1.end(), vec2.begin(), vec2.end(), dest.begin());

Example: set_intersection.cpp

std::set_difference ​

Explanation: Finds elements in one sorted range but not another.

Real-World Scenario: List items in one store but not another.

Snippet:

cpp
std::set_difference(vec1.begin(), vec1.end(), vec2.begin(), vec2.end(), dest.begin());

Example: set_difference.cpp

std::set_symmetric_difference ​

Explanation: Finds elements in either sorted range but not both.

Real-World Scenario: Identify differences between two permission sets.

Snippet:

cpp
std::set_symmetric_difference(vec1.begin(), vec1.end(), vec2.begin(), vec2.end(), dest.begin());

Example: set_symmetric_difference.cpp

std::push_heap ​

Explanation: Adds an element to a heap.

Real-World Scenario: Add a task to a priority queue in a scheduler.

Snippet:

cpp
std::push_heap(vec.begin(), vec.end());

Example: push_heap.cpp

std::pop_heap ​

Explanation: Removes the largest element from a heap.

Real-World Scenario: Retrieve the highest-priority task from a queue.

Snippet:

cpp
std::pop_heap(vec.begin(), vec.end());

Example: pop_heap.cpp

std::make_heap ​

Explanation: Converts a range into a heap.

Real-World Scenario: Initialize a priority queue for tasks.

Snippet:

cpp
std::make_heap(vec.begin(), vec.end());

Example: make_heap.cpp

std::sort_heap ​

Explanation: Sorts a heap into a sorted range.

Real-World Scenario: Convert a priority queue into a sorted list.

Snippet:

cpp
std::sort_heap(vec.begin(), vec.end());

Example: sort_heap.cpp

std::min ​

Explanation: Returns the smaller of two values.

Real-World Scenario: Find the cheaper of two products in a store.

Snippet:

cpp
std::min(a, b);

Example: min.cpp

std::max ​

Explanation: Returns the larger of two values.

Real-World Scenario: Find the higher score in a game.

Snippet:

cpp
std::max(a, b);

Example: max.cpp

std::min_element ​

Explanation: Finds the smallest element in a range.

Real-World Scenario: Identify the lowest price in a product list.

Snippet:

cpp
std::min_element(vec.begin(), vec.end());

Example: min_element.cpp

std::max_element ​

Explanation: Finds the largest element in a range.

Real-World Scenario: Find the highest score in a leaderboard.

Snippet:

cpp
std::max_element(vec.begin(), vec.end());

Example: max_element.cpp

std::lexicographical_compare ​

Explanation: Compares two ranges lexicographically.

Real-World Scenario: Sort strings in a dictionary application.

Snippet:

cpp
std::lexicographical_compare(str1.begin(), str1.end(), str2.begin(), str2.end());

Example: lexicographical_compare.cpp

std::next_permutation ​

Explanation: Generates the next permutation of a range.

Real-World Scenario: Generate all possible routes in a navigation system.

Snippet:

cpp
std::next_permutation(vec.begin(), vec.end());

Example: next_permutation.cpp

std::prev_permutation ​

Explanation: Generates the previous permutation of a range.

Real-World Scenario: Find the previous valid combination in a puzzle solver.

Snippet:

cpp
std::prev_permutation(vec.begin(), vec.end());

Example: prev_permutation.cpp

Function Objects (Functors) ​

std::unary_function ​

Explanation: Base for unary function objects (deprecated in C++11).

Real-World Scenario: Define a custom function for transforming data.

Snippet:

cpp
struct MyFunc : std::unary_function<int, int> { int operator()(int x) { return x; } };

Example: unary_function.cpp

std::binary_function ​

Explanation: Base for binary function objects (deprecated in C++11).

Real-World Scenario: Define a custom comparison for sorting.

Snippet:

cpp
struct MyComp : std::binary_function<int, int, bool> { bool operator()(int x, int y) { return x < y; } };

Example: binary_function.cpp

std::plus ​

Explanation: Adds two values.

Real-World Scenario: Sum prices in a shopping cart.

Snippet:

cpp
std::plus<int> add; add(2, 3);

Example: plus.cpp

std::minus ​

Explanation: Subtracts one value from another.

Real-World Scenario: Calculate the difference in scores.

Snippet:

cpp
std::minus<int> sub; sub(5, 3);

Example: minus.cpp

std::multiplies ​

Explanation: Multiplies two values.

Real-World Scenario: Compute total cost with quantity in a store.

Snippet:

cpp
std::multiplies<int> mul; mul(2, 3);

Example: multiplies.cpp

std::divides ​

Explanation: Divides one value by another.

Real-World Scenario: Calculate average speed in a tracking app.

Snippet:

cpp
std::divides<int> div; div(6, 2);

Example: divides.cpp

std::modulus ​

Explanation: Computes the remainder of division.

Real-World Scenario: Check if a number is even in a validator.

Snippet:

cpp
std::modulus<int> mod; mod(5, 2);

Example: modulus.cpp

std::negate ​

Explanation: Negates a value.

Real-World Scenario: Invert a value in a physics calculation.

Snippet:

cpp
std::negate<int> neg; neg(5);

Example: negate.cpp

std::equal_to ​

Explanation: Checks if two values are equal.

Real-World Scenario: Compare user inputs in a form validator.

Snippet:

cpp
std::equal_to<int> eq; eq(5, 5);

Example: equal_to.cpp

std::not_equal_to ​

Explanation: Checks if two values are not equal.

Real-World Scenario: Validate unique usernames in a system.

Snippet:

cpp
std::not_equal_to<int> neq; neq(5, 3);

Example: not_equal_to.cpp

std::greater ​

Explanation: Checks if one value is greater than another.

Real-World Scenario: Sort scores in descending order.

Snippet:

cpp
std::greater<int> gt; gt(5, 3);

Example: greater.cpp

std::less ​

Explanation: Checks if one value is less than another.

Real-World Scenario: Sort prices in ascending order.

Snippet:

cpp
std::less<int> lt; lt(3, 5);

Example: less.cpp

std::greater_equal ​

Explanation: Checks if one value is greater than or equal to another.

Real-World Scenario: Filter items with a minimum rating.

Snippet:

cpp
std::greater_equal<int> ge; ge(5, 5);

Example: greater_equal.cpp

std::less_equal ​

Explanation: Checks if one value is less than or equal to another.

Real-World Scenario: Check if a budget meets a threshold.

Snippet:

cpp
std::less_equal<int> le; le(3, 5);

Example: less_equal.cpp

std::logical_and ​

Explanation: Performs logical AND on two values.

Real-World Scenario: Check if two conditions are true in a validator.

Snippet:

cpp
std::logical_and<bool> and_op; and_op(true, true);

Example: logical_and.cpp

std::logical_or ​

Explanation: Performs logical OR on two values.

Real-World Scenario: Allow access if one of two permissions is granted.

Snippet:

cpp
std::logical_or<bool> or_op; or_op(true, false);

Example: logical_or.cpp

std::logical_not ​

Explanation: Performs logical NOT on a value.

Real-World Scenario: Invert a condition in a control system.

Snippet:

cpp
std::logical_not<bool> not_op; not_op(true);

Example: logical_not.cpp

std::unary_negate ​

Explanation: Negates the result of a unary predicate (deprecated in C++11).

Real-World Scenario: Invert a condition in a filtering algorithm.

Snippet:

cpp
std::unary_negate<MyPred> neg(pred);

Example: unary_negate.cpp

std::binary_negate ​

Explanation: Negates the result of a binary predicate (deprecated in C++11).

Real-World Scenario: Invert a comparison in a sorting algorithm.

Snippet:

cpp
std::binary_negate<MyComp> neg(comp);

Example: binary_negate.cpp

std::binder1st ​

Explanation: Binds the first argument of a binary function (deprecated in C++11).

Real-World Scenario: Fix one argument in a comparison function.

Snippet:

cpp
std::binder1st<std::plus<int>> add_to_5(std::plus<int>(), 5);

Example: binder1st.cpp

std::binder2nd ​

Explanation: Binds the second argument of a binary function (deprecated in C++11).

Real-World Scenario: Fix the second operand in a subtraction function.

Snippet:

cpp
std::binder2nd<std::minus<int>> sub_from_5(std::minus<int>(), 5);

Example: binder2nd.cpp

std::pointer_to_unary_function ​

Explanation: Converts a unary function pointer to a function object (deprecated in C++11).

Real-World Scenario: Adapt a function for use in an algorithm.

Snippet:

cpp
std::pointer_to_unary_function<int, int> func_ptr(myFunc);

Example: pointer_to_unary_function.cpp

std::pointer_to_binary_function ​

Explanation: Converts a binary function pointer to a function object (deprecated in C++11).

Real-World Scenario: Use a function pointer in a sorting algorithm.

Snippet:

cpp
std::pointer_to_binary_function<int, int, int> func_ptr(myFunc);

Example: pointer_to_binary_function.cpp

std::mem_fun ​

Explanation: Creates a function object from a member function (deprecated in C++11).

Real-World Scenario: Call a member function on objects in a container.

Snippet:

cpp
std::mem_fun(&MyClass::myMethod);

Example: mem_fun.cpp

std::mem_fun_ref ​

Explanation: Creates a function object from a member function for references (deprecated in C++11).

Real-World Scenario: Apply a member function to a container of objects.

Snippet:

cpp
std::mem_fun_ref(&MyClass::myMethod);

Example: mem_fun_ref.cpp

Utilities ​

std::pair ​

Explanation: Stores two values of different types.

Real-World Scenario: Store key-value pairs in a configuration file parser.

Snippet:

cpp
std::pair<int, string> p = {1, "value"};

Example: pair.cpp

std::string ​

Explanation: Manages sequences of characters.

Real-World Scenario: Store usernames in a login system.

Snippet:

cpp
std::string s = "hello";

Example: string.cpp

std::auto_ptr (Deprecated in C++11) ​

Explanation: Smart pointer for automatic memory management.

Real-World Scenario: Manage dynamic memory in a legacy system.

Snippet:

cpp
std::auto_ptr<int> ptr(new int(5));

Example: auto_ptr.cpp

std::rel_ops ​

Explanation: Generates relational operators from == and <.

Real-World Scenario: Simplify comparisons in a custom class.

Snippet:

cpp
using namespace std::rel_ops; bool operator==(MyClass, MyClass);

Example: rel_ops.cpp

Input/Output ​

std::iostream ​

Explanation: Provides input and output via streams.

Real-World Scenario: Read user input and display results in a console app.

Snippet:

cpp
std::cout << "Hello"; std::cin >> x;

Example: iostream.cpp

std::istream ​

Explanation: Handles input operations from streams.

Real-World Scenario: Read data from a file in a data importer.

Snippet:

cpp
std::ifstream in("file.txt"); int x; in >> x;

Example: istream.cpp

std::ostream ​

Explanation: Handles output operations to streams.

Real-World Scenario: Write logs to a file in a logging system.

Snippet:

cpp
std::ofstream out("log.txt"); out << "Log";

Example: ostream.cpp

std::stringstream ​

Explanation: Manages string-based input/output operations.

Real-World Scenario: Parse a string of numbers in a data processor.

Snippet:

cpp
std::stringstream ss; ss << "123"; int x; ss >> x;

Example: stringstream.cpp

std::fstream ​

Explanation: A stream class for both reading from and writing to files.

Real-World Scenario: Read configuration, modify values, and write back in a settings manager.

Snippet:

cpp
#include <fstream>
std::fstream file("data.txt", std::ios::in | std::ios::out);

Example: fstream.cpp

std::ifstream ​

Explanation: An input stream for reading data from files.

Real-World Scenario: Load level data from a file in a game engine.

Snippet:

cpp
#include <fstream>
std::ifstream in("level.dat"); int val; in >> val;

Example: ifstream.cpp

std::ofstream ​

Explanation: An output stream for writing data to files.

Real-World Scenario: Export a report to a CSV file in a business analytics tool.

Snippet:

cpp
#include <fstream>
std::ofstream out("report.csv"); out << "Name,Score\n";

Example: ofstream.cpp

std::streambuf ​

Explanation: The low-level buffer abstraction underlying all stream I/O, managing character sequences.

Real-World Scenario: Redirect std::cout output to a file by swapping stream buffers.

Snippet:

cpp
std::streambuf* original = std::cout.rdbuf();
std::cout.rdbuf(fileStream.rdbuf());

Example: streambuf.cpp

std::ios_base ​

Explanation: The base class for all I/O streams, managing format flags, state bits, and locale.

Real-World Scenario: Set fixed-point notation and precision for financial output formatting.

Snippet:

cpp
std::cout.setf(std::ios_base::fixed);
std::cout.precision(2);

Example: ios_base.cpp

std::cin, std::cout, std::cerr, std::clog ​

Explanation: The four standard global stream objects for console input, output, error output, and logging.

Real-World Scenario: Read user commands from cin, display results on cout, and log errors to cerr.

Snippet:

cpp
std::string name; std::cin >> name;
std::cout << "Hello " << name;
std::cerr << "Warning: low memory";

Example: standard_streams.cpp

Numeric Algorithms ​

std::accumulate ​

Explanation: Folds a range into a single value by applying a binary operation (defaults to addition).

Real-World Scenario: Calculate the total revenue from a list of daily sales in a financial report.

Snippet:

cpp
#include <numeric>
std::vector<int> v = {1, 2, 3, 4};
int sum = std::accumulate(v.begin(), v.end(), 0);

Example: accumulate.cpp

std::inner_product ​

Explanation: Computes the sum of element-wise products of two ranges (dot product by default).

Real-World Scenario: Calculate the dot product of two vectors in a physics simulation.

Snippet:

cpp
#include <numeric>
int dot = std::inner_product(a.begin(), a.end(), b.begin(), 0);

Example: inner_product.cpp

std::partial_sum ​

Explanation: Computes running cumulative sums of a range, writing results to an output range.

Real-World Scenario: Generate a cumulative total of monthly expenses for a year-to-date budget view.

Snippet:

cpp
#include <numeric>
std::partial_sum(v.begin(), v.end(), result.begin());

Example: partial_sum.cpp

std::adjacent_difference ​

Explanation: Computes the difference between consecutive elements in a range.

Real-World Scenario: Calculate day-over-day stock price changes from a time series.

Snippet:

cpp
#include <numeric>
std::adjacent_difference(v.begin(), v.end(), result.begin());

Example: adjacent_difference.cpp

Numerics ​

std::valarray ​

Explanation: A numeric array class optimized for element-wise mathematical operations.

Real-World Scenario: Apply a mathematical formula to every sample in a digital signal processing pipeline.

Snippet:

cpp
#include <valarray>
std::valarray<double> data = {1.0, 2.0, 3.0};
std::valarray<double> squared = data * data;

Example: valarray.cpp

std::complex ​

Explanation: Represents complex numbers with real and imaginary parts, supporting arithmetic operations.

Real-World Scenario: Perform FFT computations in an audio processing application.

Snippet:

cpp
#include <complex>
std::complex<double> z(3.0, 4.0); // 3 + 4i
double magnitude = std::abs(z);   // 5.0

Example: complex.cpp

std::numeric_limits ​

Explanation: Provides information about the properties of arithmetic types (min, max, precision, etc.).

Real-World Scenario: Check the maximum representable value before performing a calculation to prevent overflow.

Snippet:

cpp
#include <limits>
int maxInt = std::numeric_limits<int>::max();
bool hasInfinity = std::numeric_limits<double>::has_infinity;

Example: numeric_limits.cpp

Memory ​

std::allocator ​

Explanation: The default memory allocator used by STL containers, separating allocation from construction.

Real-World Scenario: Understand how std::vector manages memory internally, or provide a custom allocator for a memory pool.

Snippet:

cpp
#include <memory>
std::allocator<int> alloc;
int* p = alloc.allocate(10);
alloc.deallocate(p, 10);

Example: allocator.cpp

Exception Classes ​

std::exception ​

Explanation: The base class for all standard library exceptions, providing a what() message.

Real-World Scenario: Catch any standard exception in a top-level error handler.

Snippet:

cpp
try { /* ... */ } catch (const std::exception& e) { std::cerr << e.what(); }

Example: exception.cpp

std::runtime_error ​

Explanation: Exception for errors detectable only during program execution.

Real-World Scenario: Throw when a network connection fails unexpectedly.

Snippet:

cpp
throw std::runtime_error("Connection failed");

Example: runtime_error.cpp

std::logic_error ​

Explanation: Exception for errors caused by flawed program logic that could be caught before runtime.

Real-World Scenario: Throw when a function receives logically invalid parameters.

Snippet:

cpp
throw std::logic_error("Invalid state transition");

Example: logic_error.cpp

std::out_of_range ​

Explanation: Exception thrown when an index or key is outside the valid range.

Real-World Scenario: Accessing an element beyond the size of a vector via at().

Snippet:

cpp
std::vector<int> v = {1, 2}; v.at(5); // throws std::out_of_range

Example: out_of_range.cpp

std::invalid_argument ​

Explanation: Exception thrown when a function receives an argument with an invalid value.

Real-World Scenario: Parsing a string that doesn't represent a valid number.

Snippet:

cpp
int n = std::stoi("abc"); // throws std::invalid_argument

Example: invalid_argument.cpp

std::overflow_error ​

Explanation: Exception thrown when an arithmetic overflow is detected.

Real-World Scenario: Signal overflow in a custom big-integer multiplication function.

Snippet:

cpp
throw std::overflow_error("Integer overflow in multiply");

Example: overflow_error.cpp

std::underflow_error ​

Explanation: Exception thrown when an arithmetic underflow is detected.

Real-World Scenario: Signal underflow in a floating-point computation near zero.

Snippet:

cpp
throw std::underflow_error("Value too small to represent");

Example: underflow_error.cpp

std::length_error ​

Explanation: Exception thrown when an operation would exceed the maximum allowed size.

Real-World Scenario: Attempting to resize a string beyond max_size().

Snippet:

cpp
std::string s; s.resize(s.max_size() + 1); // throws std::length_error

Example: length_error.cpp

std::domain_error ​

Explanation: Exception thrown when a mathematical function is called outside its domain.

Real-World Scenario: Computing the square root of a negative number in a math library.

Snippet:

cpp
throw std::domain_error("sqrt of negative number");

Example: domain_error.cpp

std::range_error ​

Explanation: Exception thrown when a computation produces a result outside the representable range.

Real-World Scenario: A floating-point result exceeds the representable range during a physics calculation.

Snippet:

cpp
throw std::range_error("Result out of representable range");

Example: range_error.cpp

std::bad_alloc ​

Explanation: Exception thrown when new fails to allocate memory.

Real-World Scenario: Handle out-of-memory conditions gracefully in a server application.

Snippet:

cpp
try { int* p = new int[1000000000]; } catch (const std::bad_alloc& e) {}

Example: bad_alloc.cpp

std::bad_cast ​

Explanation: Exception thrown by dynamic_cast when a reference cast to an invalid type fails.

Real-World Scenario: Catch failed downcasts in a plugin system that loads unknown types.

Snippet:

cpp
try { Derived& d = dynamic_cast<Derived&>(baseRef); } catch (const std::bad_cast& e) {}

Example: bad_cast.cpp

std::bad_typeid ​

Explanation: Exception thrown when typeid is applied to a dereferenced null pointer of a polymorphic type.

Real-World Scenario: Guard against null pointer dereference in a type-inspection utility.

Snippet:

cpp
Base* p = nullptr;
try { typeid(*p); } catch (const std::bad_typeid& e) {}

Example: bad_typeid.cpp

std::bad_exception ​

Explanation: Exception thrown when an unexpected exception type violates a function's exception specification.

Real-World Scenario: Handle violations of legacy throw() specifications in older codebases.

Snippet:

cpp
void func() throw(std::bad_exception) { throw 42; }

Example: bad_exception.cpp

Localization ​

std::locale ​

Explanation: Encapsulates a set of cultural conventions for formatting numbers, dates, and text.

Real-World Scenario: Format currency values with locale-specific decimal separators in an international e-commerce app.

Snippet:

cpp
#include <locale>
std::locale loc("en_US.UTF-8");
std::cout.imbue(loc);

Example: locale.cpp

std::locale::facet ​

Explanation: The base class for locale-specific formatting categories like number formatting, collation, and character classification.

Real-World Scenario: Create a custom facet that formats phone numbers according to regional conventions.

Snippet:

cpp
#include <locale>
const std::numpunct<char>& np = std::use_facet<std::numpunct<char>>(std::locale());
char sep = np.thousands_sep();

Example: locale_facet.cpp

C Library Wrappers ​

<cmath> ​

Explanation: C++ wrapper for the C math library, providing mathematical functions like sin, cos, sqrt, pow, abs, ceil, floor, and more.

Real-World Scenario: Calculate trajectory angles and distances in a ballistics simulation.

Snippet:

cpp
#include <cmath>
double angle = std::atan2(y, x);
double dist = std::sqrt(x*x + y*y);

Example: cmath.cpp

<cstdlib> ​

Explanation: General-purpose utilities including memory allocation (malloc/free), random numbers (rand/srand), conversions (atoi/atof), and program control (exit/abort).

Real-World Scenario: Generate random enemy spawn positions in a game loop.

Snippet:

cpp
#include <cstdlib>
std::srand(42);
int roll = std::rand() % 6 + 1;

Example: cstdlib.cpp

<cstring> ​

Explanation: C-style string manipulation functions including strlen, strcpy, strcat, strcmp, memcpy, and memset.

Real-World Scenario: Parse a null-terminated string received from a C API in a cross-language integration layer.

Snippet:

cpp
#include <cstring>
char dest[20]; std::strcpy(dest, "Hello");
int len = std::strlen(dest);

Example: cstring.cpp

<cstdio> ​

Explanation: C-style formatted I/O functions including printf, scanf, fprintf, fscanf, sprintf, and FILE operations.

Real-World Scenario: Write high-performance formatted output in a logging system where stream overhead matters.

Snippet:

cpp
#include <cstdio>
std::printf("Score: %d, Time: %.2f\n", score, elapsed);

Example: cstdio.cpp

<cctype> ​

Explanation: Character classification and conversion functions including isalpha, isdigit, isspace, toupper, and tolower.

Real-World Scenario: Validate that a user-entered password contains at least one digit and one uppercase letter.

Snippet:

cpp
#include <cctype>
char c = 'a';
if (std::isalpha(c)) { c = std::toupper(c); }

Example: cctype.cpp

<climits> ​

Explanation: Defines constants for the limits of integer types such as INT_MAX, INT_MIN, LONG_MAX, CHAR_BIT, etc.

Real-World Scenario: Check if adding two integers would overflow before performing the operation.

Snippet:

cpp
#include <climits>
if (a > INT_MAX - b) { /* overflow! */ }

Example: climits.cpp

<cfloat> ​

Explanation: Defines constants for the limits of floating-point types such as FLT_MAX, FLT_MIN, DBL_EPSILON, FLT_DIG, etc.

Real-World Scenario: Compare floating-point values with an epsilon tolerance in a physics engine.

Snippet:

cpp
#include <cfloat>
bool equal = std::abs(a - b) < DBL_EPSILON;

Example: cfloat.cpp

<cassert> ​

Explanation: Provides the assert macro for runtime assertion checking, disabled in release builds with NDEBUG.

Real-World Scenario: Verify function preconditions during development to catch bugs early.

Snippet:

cpp
#include <cassert>
assert(ptr != nullptr); // aborts if ptr is null

Example: cassert.cpp

<ctime> ​

Explanation: Date and time utilities including time, clock, difftime, mktime, strftime, and the struct tm type.

Real-World Scenario: Measure the execution time of a sorting algorithm for benchmarking.

Snippet:

cpp
#include <ctime>
std::time_t start = std::time(nullptr);
// ... work ...
double elapsed = std::difftime(std::time(nullptr), start);

Example: ctime.cpp

Released under the MIT License.