What follows is a lesson plan for teaching the Standard Template Library (STL) in C++, covering the requested topics. I've organized it in a logical sequence, starting from the most foundational concepts, then moving to more advanced ones. This lesson plan is divided into sections, each with explanations and illustrative examples.
The Standard Template Library (STL) is a collection of powerful, generic components that help manage and manipulate data in C++. It provides: - Containers: For storing data. - Iterators: For traversing containers. - Algorithms: For manipulating data within containers.
Objective: By the end of this module, students will be able to use STL containers and algorithms effectively, improving code efficiency and readability.
Containers are data structures designed to store collections of objects. STL provides several types of containers, categorized as:
- Sequence Containers: array
, vector
, deque
, list
, forward_list
.
- Associative Containers: set
, map
, multiset
, multimap
.
- Unordered Associative Containers: unordered_set
, unordered_map
, unordered_multiset
, unordered_multimap
.
- Container Adaptors: stack
, queue
, priority_queue
.
We'll focus on the most commonly used ones: array
, vector
, and set
.
std::array
is a fixed-size sequence container, similar to a C-style array, but with added STL capabilities like iterators and bounds checking.std::array<T, N>
Example:
```cpp
#include
int main() {
std::array
// Access elements using at() (bounds-checked)
std::cout << "First element: " << arr.at(0) << std::endl;
// Range-based for loop (modern C++)
for (const auto& element : arr) {
std::cout << element << " ";
}
std::cout << std::endl;
return 0;
} ```
Key Points:
- Fixed size, determined at compile-time.
- Use at()
for safe access with bounds checking.
std::vector
is a dynamic array that can resize itself automatically when elements are added or removed.std::vector<T>
Example:
```cpp
#include
int main() {
std::vector
// Add elements
vec.push_back(6);
// Access using index
std::cout << "Third element: " << vec[2] << std::endl;
// Iterate using an iterator
for (auto it = vec.begin(); it != vec.end(); ++it) {
std::cout << *it << " ";
}
std::cout << std::endl;
return 0;
} ```
Key Points: - Dynamically resizable. - Supports random access (constant-time complexity). - Insertion/removal at the end is fast (amortized O(1)).
Discussion: vector
vs array
:
- Use array
when size is fixed and known at compile time.
- Use vector
when dynamic resizing is required.
std::set
is an ordered associative container that contains unique elements in a specific order.std::set<T>
Example:
```cpp
#include
int main() {
std::set
// Insert elements
s.insert(6);
// Elements are stored in sorted order
for (const auto& element : s) {
std::cout << element << " ";
}
std::cout << std::endl;
// Find element
if (s.find(3) != s.end()) {
std::cout << "Element 3 found!" << std::endl;
}
return 0;
} ```
Key Points: - Stores unique elements in sorted order. - Average time complexity of operations (insert, find) is O(log n).
Discussion: set
vs vector
:
- Use set
when you need uniqueness and fast look-up.
- Use vector
when order of insertion matters, and duplicates are allowed.
Example: Iterating over a std::vector
using iterators.
```cpp
#include
int main() {
std::vector
// Iterator-based loop
for (auto it = vec.begin(); it != vec.end(); ++it) {
std::cout << *it << " ";
}
std::cout << std::endl;
return 0;
} ```
Key Points: - Iterators provide a uniform way to traverse containers. - They decouple the algorithm from the container.
Discussion: Raw Loops vs Iterators vs Range-based Loops: - Raw loops give more control but are error-prone. - Iterators provide container-agnostic traversal. - Range-based loops simplify iteration, especially for read-only access.
#include <algorithm>
Example: Sorting and finding elements in a std::vector
.
```cpp
#include
int main() {
std::vector
// Sort the vector
std::sort(vec.begin(), vec.end());
// Display sorted elements
for (const auto& element : vec) {
std::cout << element << " ";
}
std::cout << std::endl;
// Find an element
auto it = std::find(vec.begin(), vec.end(), 30);
if (it != vec.end()) {
std::cout << "Element 30 found at index " << std::distance(vec.begin(), it) << std::endl;
}
return 0;
} ```
Key Points:
- std::sort
uses a highly optimized quicksort/intro-sort algorithm (O(n log n)).
- std::find
performs linear search (O(n)).
Discussion: Using Algorithms vs Manual Loops: - Algorithms are more concise and often better optimized than hand-written loops. - Use STL algorithms when possible for better code clarity and efficiency.
Objective: Demonstrating how to use containers with iterators and algorithms together.
Example: Using std::set
with std::transform
to modify its elements.
```cpp
#include
int main() {
std::set
// Use transform algorithm to square each element
std::transform(s.begin(), s.end(), std::back_inserter(result), [](int x) { return x * x; });
// Display the result
for (const auto& element : result) {
std::cout << element << " ";
}
std::cout << std::endl;
return 0;
} ```
Key Points: - Algorithms work with various containers using iterators. - Lambda functions can be passed to algorithms for customization.
vector
for dynamic arrays, set
for sorted unique elements, etc.Homework Assignment:
1. Write a program that reads integers from the user, stores them in a std::vector
, and then sorts the vector in descending
order using an STL algorithm.
2. Implement a std::set
that stores unique words from a given text file and prints them in alphabetical order.
This lesson plan provides a solid foundation for understanding the STL, with clear examples and explanations of how containers, iterators, and algorithms interact.
Previous Page | Course Schedule | Course Content