Skip to main content
C++ Fundamentals for Beginners to Advanced
CHAPTER 22 Beginner

Standard Template Library (STL)

Updated: May 17, 2026
5 min read

# CHAPTER 22

Standard Template Library (STL)

1. Introduction

If you need a dynamic array in C++, you *could* write a class, manage pointers, use new and delete, and manually resize memory when it gets full. OR... you could just use std::vector. The Standard Template Library (STL) is a massive collection of pre-written, highly optimized data structures (Containers) and Algorithms. It is the most powerful tool in a C++ developer's arsenal.

2. Learning Objectives

By the end of this chapter, you will be able to:
  • Understand the three core components of the STL: Containers, Iterators, and Algorithms.
  • Use std::vector for dynamic arrays.
  • Use std::map and std::set for associative data.
  • Navigate containers using Iterators.
  • Apply STL Algorithms like sort().

3. Core Components of STL

  1. 1. Containers: Objects that store data (e.g., Vector, List, Map).
  1. 2. Algorithms: Functions that process data (e.g., sort, search, reverse).
  1. 3. Iterators: Special pointers used to navigate through Containers safely.

4. Vector (Dynamic Array)

A vector is an array that automatically grows in size when you add elements to it. *(Requires #include <vector>)*
cpp
1234567891011121314151617181920212223
#include <iostream>
#include <vector>
using namespace std;

int main() {
    vector<int> scores; // Creates an empty dynamic array of integers
    
    // Add elements to the END of the vector
    scores.push_back(100);
    scores.push_back(85);
    scores.push_back(95);
    
    // Access like a normal array
    cout << "First score: " << scores[0] << endl;
    
    // Get current size
    cout << "Total elements: " << scores.size() << endl;
    
    // Remove the last element
    scores.pop_back(); 
    
    return 0;
}

5. Iterators

Iterators act like pointers designed specifically to step through STL containers.
cpp
123456789101112
vector<string> names = {"Alice", "Bob", "Charlie"};

// Traditional iterator syntax
vector<string>::iterator it;
for (it = names.begin(); it != names.end(); it++) {
    cout << *it << " "; // Dereference iterator to get value
}

// MODERN C++ WAY (Much cleaner using 'auto' and range-based for loop)
for (auto name : names) {
    cout << name << " ";
}

6. Map (Key-Value Pairs)

A map stores data in Key-Value pairs (like a Dictionary in Python). Keys must be unique. It automatically sorts the data by the Keys! *(Requires #include <map>)*
cpp
12345678910111213141516171819
#include <iostream>
#include <map>
using namespace std;

int main() {
    map<string, int> ages; // Key is string, Value is int
    
    ages["Alice"] = 25;
    ages["Bob"] = 30;
    
    cout << "Bob is " << ages["Bob"] << " years old." << endl;
    
    // Iterating through a map
    for (auto pair : ages) {
        cout << pair.first << " is " << pair.second << endl; 
        // pair.first is the Key, pair.second is the Value
    }
    return 0;
}

7. Set (Unique Elements)

A set stores only UNIQUE elements and automatically sorts them in ascending order. *(Requires #include <set>)*
cpp
12345678
#include <set>
// ...
set<int> numbers;
numbers.insert(10);
numbers.insert(5);
numbers.insert(10); // Ignored! 10 is already in the set.

// Prints: 5 10 (Automatically sorted and duplicates removed)

8. STL Algorithms

The <algorithm> library contains dozens of functions to manipulate containers.
cpp
123456789101112131415161718
#include <iostream>
#include <vector>
#include <algorithm> // Required for sort()
using namespace std;

int main() {
    vector<int> v = {50, 10, 30, 20, 40};
    
    // Sort ascending
    sort(v.begin(), v.end()); 
    // v is now: 10, 20, 30, 40, 50
    
    // Reverse the vector
    reverse(v.begin(), v.end());
    // v is now: 50, 40, 30, 20, 10
    
    return 0;
}

9. Memory-Level Explanation (vector)

How does a vector grow dynamically?
  1. 1. It starts with a fixed capacity on the Heap (e.g., 4 elements).
  1. 2. When you push the 5th element, it allocates a NEW block of memory *double* the size (8 elements).
  1. 3. It copies the old elements to the new block.
  1. 4. It deletes the old block.
*(This is why vectors are slightly slower than standard arrays when resizing heavily, but you can optimize this using v.reserve(100)).*

10. Common Mistakes

  • Accessing out-of-bounds with [ ]: v[10] on a 5-element vector will corrupt memory. Use v.at(10) instead; it throws a safe std::outofrange exception!
  • Modifying a map/vector while iterating: Adding or removing elements while looping through a container with an iterator can invalidate the iterator and crash the program.

11. Exercises

  1. 1. Create a vector of strings. Ask the user to input 5 names. Use std::sort() to alphabetize them, then print them.
  1. 2. Create a map storing country names as keys and their capitals as values. Look up a capital by passing a country name.

12. MCQ Quiz with Answers

Question 1

Which STL container is best for a dynamically resizing array?

Question 2

Which STL container stores Key-Value pairs?

Question 3

What does a set automatically do?

Question 4

Which function adds an element to the end of a vector?

Question 5

What are Iterators?

Question 6

Which library is required to use the sort() function?

Question 7

How do you access the value in a map's iterator/pair?

Question 8

What is the safer alternative to vector[10]?

Question 9

If a vector runs out of capacity, what does it typically do behind the scenes?

Q10. Can you sort a standard C++ array using std::sort()? a) Yes (e.g., sort(arr, arr + size);) b) No, it only works on vectors Answer: a) Yes (e.g., sort(arr, arr + size);)

13. Interview Questions

  • Q: Explain the difference between std::vector and std::list. When would you use one over the other? (Hint: contiguous memory vs doubly-linked nodes).
  • Q: How is std::map implemented under the hood? (Answer: Red-Black Tree).
  • Q: Explain Iterator Invalidation.

14. Summary

The Standard Template Library (STL) provides robust, high-performance Containers (Vectors, Maps, Sets) and Algorithms (sorting, searching). By leveraging iterators, you can write powerful, generic code without manually managing pointers or memory resizing.

15. Next Chapter Recommendation

In Chapter 23: File Handling in C++, we will learn how to save our data permanently to the hard drive by reading and writing text files.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·