Notes

πŸ“˜ Introduction to C++ Standard Template Library (STL)

πŸ”· What is STL?

The Standard Template Library (STL) is a powerful set of C++ template classes designed to provide general-purpose classes and functions with templates. You can think of STL as a toolbox that provides ready-to-use tools to work with data effectively and efficiently.

  • STL (Standard Template Library) is a library of components that are commonly used in C++.
  • It is like a toolbox that can be used when building things with C++.
  • Inside STL toolbox there are tools (components) for different kinds of data.

πŸ’‘ Analogy: STL is like a toolbox for C++ developers β€” it contains a variety of tools such as containers, algorithms, iterators, and more that simplify programming and improve efficiency.


πŸ”· Why Do We Need STL?

  • 🧠 Efficiency: STL is highly optimized and helps you write faster, cleaner, and bug-free code.

  • πŸ” Reusability: Provides generic code using templates, so the same function or class can work with multiple data types.

  • 🧹 Clean Code: Reduces redundancy and makes code more readable and maintainable.

  • πŸš€ Productivity: Allows developers to focus more on solving problems than reinventing basic structures or algorithms.


πŸ”· Major Components of STL

STL is mainly divided into four key components:

  • Containers
    • Containers are boxes in which we store data that requires processing.
    • The most commonly used containers are vector, list, map, set, stack, queue, etc.
    • Each container provides different capabilities and benefits.
  • Algorithms
    • Set of instructions that process data and give output.
    • Algorithms are like recipes for computers. Just like you follow a recipe to make your favorite food, computers use algorithms to tell them what to do with the data.
    • There are multiple algorithms already included in STL, such as algorithms for sorting, searching, grouping, comparing the data, etc.
  • Function Objects (Functors)
    • As we already said, STL comes with a lot of included algorithms, but if we want to create our own custom algorithm or to modify the existing algorithm, we can do that using Functors.
    • Functor is a custom implementation of algorithm.
    • For example, STL knows how to sort numbers by default, but it can’t know how to sort Students or some other custom data type. To sort Students by grade we can modify the Sort algorithm with our custom logic, and for that we use functors.
  • Iterators
    • Iterators are used for navigating through the data inside containers.
    • The easiest way to visualize an iterator at work is to think about the cursor moving while we are typing the text. The same way we use cursor for navigating through the text in the document, algorithms use iterators to navigate through the data inside a container.
ComponentPurpose
πŸ“¦ ContainersStore and manage data efficiently
βš™οΈ AlgorithmsProcess and manipulate data
πŸ’‘ Function Objects (Functors)Custom behaviors for algorithms
🧭 IteratorsTraverse and access data in containers

1. πŸ“¦ Containers: Storage Units for Data

Containers are objects that store collections of other objects. Each container is optimized for a specific kind of data handling (e.g., fast access, fast insertion, ordering).

πŸ“š Types of Containers:

ContainerDescription
vectorDynamic array (resizable), fast access
listDoubly-linked list, efficient insertion/removal
dequeDouble-ended queue, fast at both ends
stackLIFO (last in, first out)
queueFIFO (first in, first out)
priority_queueMax/min heap-like structure
setStores unique elements, sorted
mapKey-value pair, sorted by key
unordered_set, unordered_mapFaster (hash-based) versions of set and map

βœ… Use containers to store the data before performing operations like sorting, searching, filtering, etc.


2. βš™οΈ Algorithms: Predefined Operations

STL provides a rich set of algorithms to manipulate the data stored in containers.

πŸ”§ Examples of STL Algorithms:

  • sort(begin, end)

  • find(begin, end, value)

  • count(begin, end, value)

  • reverse(begin, end)

  • accumulate(begin, end, initial)

  • min_element, max_element

🧠 STL algorithms work seamlessly with iterators, so they can operate on any container that supports them.


3. πŸ’‘ Function Objects / Functors: Custom Algorithm Behavior

A function object (also called a functor) is an object that acts like a function. It’s used to customize the behavior of STL algorithms.

πŸ› οΈ Why Use Functors?

  • To define custom sorting rules, filters, or comparisons.

  • To pass stateful behavior into an algorithm (unlike a simple function).

πŸ§ͺ Example:

struct CompareByLength {
    bool operator()(const string &a, const string &b) {
        return a.length() < b.length(); // Sort by length
    }
};
 
sort(words.begin(), words.end(), CompareByLength());

⚠️ Functors allow greater flexibility and are more powerful than regular functions in many contexts.


4. 🧭 Iterators: Navigators of Containers

An iterator is an object that enables traversal of a container. You can think of it like a cursor or pointer.

🧭 Types of Iterators:

TypeUse
begin() / end()Start and end of a container
rbegin() / rend()Reverse start and end
advance()Moves the iterator forward
next() / prev()Gets next or previous position

πŸ§ͺ Example:

vector<int> nums = {10, 20, 30};
 
for (vector<int>::iterator it = nums.begin(); it != nums.end(); ++it) {
    cout << *it << " ";
}

πŸ” Iterators abstract container traversal, so STL algorithms can work on different containers in the same way.


πŸ”· Templates in STL: The Secret Sauce

STL is built entirely using templates, which is why it’s called the Standard Template Library.

  • Templates
    • STL is very efficient because it uses Templates.
    • Templates are generic code. They allow us to write a single piece of code that can work with different data types.
    • For example, with templates, we can write just one function, but it will work with multiple data types.

πŸ” What are Templates?

Templates are a feature in C++ that allow functions and classes to work with any data type without rewriting the code for each type.

πŸ§ͺ Example: Function Template

template <typename T>
void printData(T data) {
    cout << data << endl;
}
 
printData(5);       // int
printData("Hello"); // string

βœ… Templates help in reducing code duplication, increasing code reusability, and improving maintainability.


🧠 Summary of Key Concepts

ComponentDescription
ContainersStore data (e.g., vector, list, map)
AlgorithmsProcess data (e.g., sort, find)
FunctorsCustomize behavior of algorithms
IteratorsTraverse containers like pointers
TemplatesGeneric programming for flexibility

πŸš€ Benefits of Using STL

  • 🧱 Reduces boilerplate code

  • πŸ“ˆ Improves performance (internally optimized)

  • πŸ”§ Offers ready-to-use tools

  • πŸ›‘οΈ Helps in writing bug-free code

  • 🧰 Facilitates clean, scalable, and maintainable applications


References