C++ STL Overview

Introduction to the Standard Template Library

📚 What is STL?

STL (Standard Template Library) is a collection of pre-written C++ classes and functions including containers, algorithms, and iterators that make programming easier and more efficient.


#include <vector>
#include <iostream>
using namespace std;

vector<int> numbers = {1, 2, 3, 4, 5};
cout << "Size: " << numbers.size() << endl;
                                    

Output:

Size: 5

STL Components

📦

Containers

Store and organize data

vector<int> v;
list<string> l;
stack<int> s;
🔄

Iterators

Navigate through containers

vector<int>::iterator it;
for(it = v.begin(); it != v.end(); ++it)
⚙️

Algorithms

Pre-built functions for operations

sort(v.begin(), v.end());
find(v.begin(), v.end(), 5);
🔧

Function Objects

Callable objects for algorithms

greater<int>() // For sorting
plus<int>() // For operations

🔹 Container Types

The C++ Standard Template Library (STL) offers a versatile suite of containers categorized by sequence, associative, unordered associative, and adapters. Sequence containers (vector, list, deque) store elements in a linear order. Associative containers (set, map) store sorted keys. Unordered counterparts use hashing for speed. Adapters (stack, queue, priority_queue) provide specialized interfaces. Each type optimizes for different access patterns, insertion/deletion costs, and memory layouts. Choosing the right container is crucial for writing efficient, clear, and maintainable C++ programs tailored to specific data handling needs.

🔸 Sequence Containers

#include <vector>
#include <list>
#include <deque>

// Vector - dynamic array
vector<int> vec = {1, 2, 3};
vec.push_back(4);

// List - doubly linked list  
list<string> lst = {"apple", "banana"};
lst.push_front("orange");

// Deque - double-ended queue
deque<int> dq = {10, 20};
dq.push_front(5);
dq.push_back(30);

🔸 Container Adapters

#include <stack>
#include <queue>

// Stack - LIFO (Last In, First Out)
stack<int> stk;
stk.push(10);
stk.push(20);

// Queue - FIFO (First In, First Out)
queue<string> q;
q.push("first");
q.push("second");

🔹 Basic STL Example

A basic STL example demonstrates container usage, algorithm application, and iterator-based traversal in a cohesive program. Common tasks include populating a vector, sorting it with std::sort, and searching with std::find. This showcases the STL's philosophy: separate data (containers) from operations (algorithms) via iterators. Such examples highlight code brevity, safety from manual memory management, and performance from optimized implementations. They serve as foundational patterns for real-world applications, from data processing to system utilities, emphasizing the power and elegance of generic programming in C++.

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int main() {
    // Create vector
    vector<int> numbers = {64, 34, 25, 12, 22, 11, 90};
    
    cout << "Original: ";
    for(int num : numbers) {
        cout << num << " ";
    }
    cout << endl;
    
    // Sort using STL algorithm
    sort(numbers.begin(), numbers.end());
    
    cout << "Sorted: ";
    for(int num : numbers) {
        cout << num << " ";
    }
    cout << endl;
    
    // Find element
    auto it = find(numbers.begin(), numbers.end(), 25);
    if(it != numbers.end()) {
        cout << "Found 25 at position: " << (it - numbers.begin()) << endl;
    }
    
    return 0;
}

Output:

Original: 64 34 25 12 22 11 90
Sorted: 11 12 22 25 34 64 90
Found 25 at position: 3

🔹 STL Benefits

Using the STL in C++ programs provides significant advantages in productivity, performance, safety, and maintainability. It offers rigorously tested, optimized data structures and algorithms, reducing boilerplate and bug-prone manual implementations. Generic programming with templates ensures type safety and code reusability. The consistent iterator interface decouples algorithms from containers, promoting flexible, composable code. Furthermore, STL components are standardized and widely understood, improving code readability and collaboration. Adopting the STL is considered a best practice for modern C++, enabling developers to build robust, efficient applications faster.

Advantages:

  • Efficiency: Optimized implementations
  • Reusability: Pre-written, tested code
  • Consistency: Standard interface across containers
  • Flexibility: Generic programming with templates
  • Productivity: Less code to write and debug
// Without STL - manual array sorting
void bubbleSort(int arr[], int n) {
    for(int i = 0; i < n-1; i++) {
        for(int j = 0; j < n-i-1; j++) {
            if(arr[j] > arr[j+1]) {
                swap(arr[j], arr[j+1]);
            }
        }
    }
}

// With STL - one line!
sort(vec.begin(), vec.end());

🧠 Test Your Knowledge

What does STL stand for?