C, C++, MFC  

Chapter 15: Standard Template Library (STL): Containers in C++

Previous chapter: Chapter 14: Templates and Generic Programming in C++

The Standard Template Library (STL) is a collection of pre-written, highly efficient C++ components. It is built entirely on the template concepts from Chapter 14. The STL is divided into three main components: Containers, Iterators, and Algorithms.

This chapter focuses on Containers, which are objects that store data.

1. std::vector: The Dynamic Array

The std::vector is the most commonly used container. It acts like a regular array (Chapter 6) but can dynamically resize itself to accommodate new elements.

FeatureDescription
Header<vector>
AccessFast random access using [] or .at()
StorageElements are stored contiguously in memory

Key Vector Operations

#include <vector>

std::vector<int> numbers = {10, 20};

numbers.push_back(30);       // Adds 30 to the end. Size is 3.
numbers.insert(numbers.begin() + 1, 15); // Inserts 15 at index 1.
numbers.pop_back();          // Removes 30.
numbers.size();              // Returns current size (3).
numbers.clear();             // Empties the vector. Size is 0.

2. std::list: The Doubly-Linked List

The std::list is a container that stores non-contiguous elements linked together by pointers. It excels at fast insertions and deletions anywhere in the list.

FeatureDescription
Header<list>
AccessSlow sequential access (must traverse links)
StorageElements are scattered in memory

Key List Operations

#include <list>

std::list<std::string> names = {"Alice", "Bob", "Charlie"};

names.push_front("Zoe"); // Fast insertion at the start.
names.push_back("David"); // Fast insertion at the end.
names.remove("Bob");     // Removes all instances of "Bob".

3. std::map: Key-Value Storage

The std::map is an associative container that stores elements as key-value pairs. It is often referred to as a dictionary or hash map in other languages. Keys are unique and stored in sorted order.

FeatureDescription
Header<map>
AccessFast lookup by key (logarithmic time)
StorageUnique keys, automatically sorted

Key Map Operations

#include <map>

// Key type is string, Value type is int
std::map<std::string, int> ages;

ages["John"] = 30; // Insert or update
ages["Mary"] = 25;

std::cout << "John's age: " << ages["John"] << std::endl; // Access by key

// Checking existence (using C++20 standard)
if (ages.contains("Mary")) { 
    ages.erase("Mary");
}

These containers provide flexible and efficient ways to organize data without having to manage raw pointers or arrays manually.