Introduction
In this lab, you will learn how to use various components of the C++ Standard Template Library (STL) to create and manipulate data structures such as vectors, lists, maps, sets, and more. You'll explore the basic operations of these STL containers, including adding, removing, and iterating through elements. Additionally, you'll discover how to leverage STL algorithms for sorting, searching, and processing data within these containers. By the end of this lab, you will have a solid understanding of how to leverage the power and flexibility of the C++ STL to build efficient and robust applications.
Create and Manipulate Vector Container
In this step, you'll learn about the C++ Standard Template Library (STL) vector container, which is a dynamic array that can grow and shrink in size. Vectors are incredibly useful for storing and manipulating collections of elements.
First, open the WebIDE and create a new file called vector_demo.cpp in the ~/project directory. We'll explore the basic operations of vectors step by step.
touch ~/project/vector_demo.cpp
Add the following code to the vector_demo.cpp file:
#include <iostream>
#include <vector>
int main() {
// Create an empty vector of integers
std::vector<int> numbers;
// Add elements to the vector using push_back()
numbers.push_back(10);
numbers.push_back(20);
numbers.push_back(30);
// Print the size of the vector
std::cout << "Vector size: " << numbers.size() << std::endl;
// Access elements using index
std::cout << "First element: " << numbers[0] << std::endl;
std::cout << "Second element: " << numbers[1] << std::endl;
// Iterate through the vector using a range-based for loop
std::cout << "All elements: ";
for (int num : numbers) {
std::cout << num << " ";
}
std::cout << std::endl;
// Remove the last element
numbers.pop_back();
// Check the new size after removing an element
std::cout << "Vector size after pop_back(): " << numbers.size() << std::endl;
return 0;
}
Compile and run the program:
g++ vector_demo.cpp -o vector_demo
./vector_demo
Example output:
Vector size: 3
First element: 10
Second element: 20
All elements: 10 20 30
Vector size after pop_back(): 2
Key points about vectors:
- Use
#include <vector>to include the vector library std::vector<type>creates a vector of a specific typepush_back()adds elements to the end of the vectorsize()returns the number of elements- Access elements using index
[] pop_back()removes the last element- Range-based for loop is an easy way to iterate through vectors
Use List for Linked List Operations
In this step, you'll learn about the C++ STL list container, which implements a doubly-linked list. Lists provide efficient insertion and deletion operations at any position in the container.
Open the WebIDE and create a new file called list_demo.cpp in the ~/project directory:
touch ~/project/list_demo.cpp
Add the following code to the list_demo.cpp file:
#include <iostream>
#include <list>
int main() {
// Create an empty list of integers
std::list<int> numbers;
// Add elements to the list
numbers.push_back(10); // Add to the end
numbers.push_front(5); // Add to the beginning
numbers.push_back(20);
// Print the list size
std::cout << "List size: " << numbers.size() << std::endl;
// Iterate through the list
std::cout << "List elements: ";
for (int num : numbers) {
std::cout << num << " ";
}
std::cout << std::endl;
// Remove elements
numbers.pop_front(); // Remove first element
numbers.pop_back(); // Remove last element
// Insert an element at a specific position
auto it = numbers.begin();
numbers.insert(it, 15);
// Print updated list
std::cout << "Updated list: ";
for (int num : numbers) {
std::cout << num << " ";
}
std::cout << std::endl;
// Check if list is empty
std::cout << "Is list empty? "
<< (numbers.empty() ? "Yes" : "No") << std::endl;
return 0;
}
Compile and run the program:
g++ list_demo.cpp -o list_demo
./list_demo
Example output:
List size: 3
List elements: 5 10 20
Updated list: 15 10
Is list empty? No
Key points about lists:
- Use
#include <list>to include the list library push_back()adds elements to the endpush_front()adds elements to the beginningpop_front()andpop_back()remove elementsinsert()allows adding elements at a specific positionbegin()returns an iterator to the first elementempty()checks if the list is empty
Implement Key-Value Pairs with Map
In this step, you'll learn about the C++ STL map container, which stores key-value pairs in a sorted and unique key order. Maps are useful for creating dictionaries or associative arrays.
Open the WebIDE and create a new file called map_demo.cpp in the ~/project directory:
touch ~/project/map_demo.cpp
Add the following code to the map_demo.cpp file:
#include <iostream>
#include <map>
#include <string>
int main() {
// Create a map to store student names and their ages
std::map<std::string, int> students;
// Insert key-value pairs
students["Alice"] = 20;
students["Bob"] = 22;
students["Charlie"] = 21;
// Access values using keys
std::cout << "Alice's age: " << students["Alice"] << std::endl;
// Check if a key exists
if (students.count("David") == 0) {
std::cout << "David is not in the map" << std::endl;
}
// Iterate through the map
std::cout << "All students:" << std::endl;
for (const auto& student : students) {
std::cout << student.first << ": " << student.second << std::endl;
}
// Remove a key-value pair
students.erase("Bob");
// Check the size of the map
std::cout << "Number of students: " << students.size() << std::endl;
return 0;
}
Compile and run the program:
g++ map_demo.cpp -o map_demo
./map_demo
Example output:
Alice's age: 20
David is not in the map
All students:
Alice: 20
Bob: 22
Charlie: 21
Number of students: 2
Key points about maps:
- Use
#include <map>to include the map library map<KeyType, ValueType>creates a map with specified key and value types- Access values using square brackets
[] count()checks if a key exists- Iterate through maps using range-based for loop
erase()removes a key-value pairsize()returns the number of elements
Store Unique Elements Using Set
In this step, you'll learn about the C++ STL set container, which stores unique elements in a sorted order. Sets automatically prevent duplicate values and maintain elements in a specific order.
Open the WebIDE and create a new file called set_demo.cpp in the ~/project directory:
touch ~/project/set_demo.cpp
Add the following code to the set_demo.cpp file:
#include <iostream>
#include <set>
int main() {
// Create a set of integers
std::set<int> numbers;
// Insert elements
numbers.insert(10);
numbers.insert(20);
numbers.insert(30);
numbers.insert(10); // Duplicate, will not be added
// Print the size of the set
std::cout << "Set size: " << numbers.size() << std::endl;
// Iterate through the set
std::cout << "Set elements: ";
for (int num : numbers) {
std::cout << num << " ";
}
std::cout << std::endl;
// Check if an element exists
if (numbers.count(20) > 0) {
std::cout << "20 is in the set" << std::endl;
}
// Remove an element
numbers.erase(20);
// Check the size after removal
std::cout << "Set size after removal: " << numbers.size() << std::endl;
// Clear the set
numbers.clear();
// Check if the set is empty
std::cout << "Is set empty? "
<< (numbers.empty() ? "Yes" : "No") << std::endl;
return 0;
}
Compile and run the program:
g++ set_demo.cpp -o set_demo
./set_demo
Example output:
Set size: 3
Set elements: 10 20 30
20 is in the set
Set size after removal: 2
Is set empty? Yes
Key points about sets:
- Use
#include <set>to include the set library set<type>creates a set of unique elementsinsert()adds elements (duplicates are ignored)count()checks element existenceerase()removes an elementclear()removes all elementsempty()checks if the set is empty- Elements are automatically sorted
Sort Elements with STL sort Algorithm
In this step, you'll learn how to use the STL sort algorithm to arrange elements in ascending or descending order. The <algorithm> library provides powerful sorting capabilities for various containers.
Open the WebIDE and create a new file called sort_demo.cpp in the ~/project directory:
touch ~/project/sort_demo.cpp
Add the following code to the sort_demo.cpp file:
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
// Create a vector of integers
std::vector<int> numbers = {5, 2, 8, 1, 9, 3};
// Print original vector
std::cout << "Original vector: ";
for (int num : numbers) {
std::cout << num << " ";
}
std::cout << std::endl;
// Sort the vector in ascending order
std::sort(numbers.begin(), numbers.end());
// Print sorted vector
std::cout << "Sorted vector (ascending): ";
for (int num : numbers) {
std::cout << num << " ";
}
std::cout << std::endl;
// Sort the vector in descending order
std::sort(numbers.begin(), numbers.end(), std::greater<int>());
// Print vector sorted in descending order
std::cout << "Sorted vector (descending): ";
for (int num : numbers) {
std::cout << num << " ";
}
std::cout << std::endl;
return 0;
}
Compile and run the program:
g++ sort_demo.cpp -o sort_demo
./sort_demo
Example output:
Original vector: 5 2 8 1 9 3
Sorted vector (ascending): 1 2 3 5 8 9
Sorted vector (descending): 9 8 5 3 2 1
Key points about STL sort:
- Include
<algorithm>library for sorting std::sort()works with various containers- Default sorting is in ascending order
std::greater<type>()sorts in descending order- Sorting is done in-place, modifying the original container
- Works efficiently with different container types
Find Elements Using STL Algorithms
In this step, you'll learn how to use STL algorithms to find and search for elements in containers. The <algorithm> library provides powerful functions for searching and locating elements.
Open the WebIDE and create a new file called find_demo.cpp in the ~/project directory:
touch ~/project/find_demo.cpp
Add the following code to the find_demo.cpp file:
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
// Create a vector of integers
std::vector<int> numbers = {5, 2, 8, 1, 9, 3, 8};
// Find first occurrence of a specific element
auto it = std::find(numbers.begin(), numbers.end(), 8);
if (it != numbers.end()) {
std::cout << "First occurrence of 8 at index: "
<< std::distance(numbers.begin(), it) << std::endl;
}
// Count occurrences of an element
int count = std::count(numbers.begin(), numbers.end(), 8);
std::cout << "Number of 8s in the vector: " << count << std::endl;
// Find if any element is greater than 6
bool has_large_element = std::any_of(numbers.begin(), numbers.end(),
[](int n) { return n > 6; });
std::cout << "Vector has element > 6: "
<< (has_large_element ? "Yes" : "No") << std::endl;
// Find the minimum and maximum elements
auto min_it = std::min_element(numbers.begin(), numbers.end());
auto max_it = std::max_element(numbers.begin(), numbers.end());
std::cout << "Minimum element: " << *min_it << std::endl;
std::cout << "Maximum element: " << *max_it << std::endl;
return 0;
}
Compile and run the program:
g++ find_demo.cpp -o find_demo
./find_demo
Example output:
First occurrence of 8 at index: 2
Number of 8s in the vector: 2
Vector has element > 6: Yes
Minimum element: 1
Maximum element: 9
Key points about STL search algorithms:
std::find()locates first occurrence of an elementstd::count()counts element occurrencesstd::any_of()checks if any element meets a conditionstd::min_element()andstd::max_element()find extreme values- Lambda functions can be used for custom search conditions
- Return iterators point to found elements
Iterate Through Containers
In this step, you'll learn different ways to iterate through STL containers using various iteration techniques. We'll explore range-based for loops, iterators, and traditional index-based iteration.
Open the WebIDE and create a new file called iteration_demo.cpp in the ~/project directory:
touch ~/project/iteration_demo.cpp
Add the following code to the iteration_demo.cpp file:
#include <iostream>
#include <vector>
#include <list>
#include <map>
int main() {
// Vector iteration
std::vector<int> numbers = {10, 20, 30, 40, 50};
// Method 1: Range-based for loop (most modern and readable)
std::cout << "Vector iteration (range-based for):" << std::endl;
for (int num : numbers) {
std::cout << num << " ";
}
std::cout << std::endl;
// Method 2: Iterator-based iteration
std::cout << "Vector iteration (iterators):" << std::endl;
for (auto it = numbers.begin(); it != numbers.end(); ++it) {
std::cout << *it << " ";
}
std::cout << std::endl;
// Method 3: Index-based iteration
std::cout << "Vector iteration (index-based):" << std::endl;
for (size_t i = 0; i < numbers.size(); ++i) {
std::cout << numbers[i] << " ";
}
std::cout << std::endl;
// Map iteration
std::map<std::string, int> ages = {
{"Alice", 25},
{"Bob", 30},
{"Charlie", 35}
};
std::cout << "Map iteration:" << std::endl;
for (const auto& pair : ages) {
std::cout << pair.first << ": " << pair.second << std::endl;
}
return 0;
}
Compile and run the program:
g++ iteration_demo.cpp -o iteration_demo
./iteration_demo
Example output:
Vector iteration (range-based for):
10 20 30 40 50
Vector iteration (iterators):
10 20 30 40 50
Vector iteration (index-based):
10 20 30 40 50
Map iteration:
Alice: 25
Bob: 30
Charlie: 35
Key points about container iteration:
- Range-based for loops are the most modern and readable
- Iterators provide fine-grained control over container traversal
- Index-based iteration works well with random-access containers
autokeyword helps with type inference- Different containers support different iteration methods
Use STL Stack and Queue
In this step, you'll learn about two important STL container adapters: stack and queue. These containers provide specialized operations for last-in-first-out (LIFO) and first-in-first-out (FIFO) data management.
Open the WebIDE and create a new file called stack_queue_demo.cpp in the ~/project directory:
touch ~/project/stack_queue_demo.cpp
Add the following code to the stack_queue_demo.cpp file:
#include <iostream>
#include <stack>
#include <queue>
int main() {
// Stack demonstration
std::stack<int> myStack;
// Push elements onto the stack
myStack.push(10);
myStack.push(20);
myStack.push(30);
std::cout << "Stack operations:" << std::endl;
std::cout << "Top element: " << myStack.top() << std::endl;
// Remove top element
myStack.pop();
std::cout << "Top element after pop: " << myStack.top() << std::endl;
std::cout << "Stack size: " << myStack.size() << std::endl;
// Queue demonstration
std::queue<std::string> myQueue;
// Add elements to the queue
myQueue.push("Alice");
myQueue.push("Bob");
myQueue.push("Charlie");
std::cout << "\nQueue operations:" << std::endl;
std::cout << "Front element: " << myQueue.front() << std::endl;
std::cout << "Back element: " << myQueue.back() << std::endl;
// Remove front element
myQueue.pop();
std::cout << "Front element after pop: " << myQueue.front() << std::endl;
std::cout << "Queue size: " << myQueue.size() << std::endl;
return 0;
}
Compile and run the program:
g++ stack_queue_demo.cpp -o stack_queue_demo
./stack_queue_demo
Example output:
Stack operations:
Top element: 30
Top element after pop: 20
Stack size: 2
Queue operations:
Front element: Alice
Back element: Charlie
Front element after pop: Bob
Queue size: 2
Key points about stack and queue:
- Stack (LIFO - Last In, First Out)
push()adds element to the toppop()removes top elementtop()returns the top element
- Queue (FIFO - First In, First Out)
push()adds element to the backpop()removes front elementfront()returns the first elementback()returns the last element
- Both have
size()method to check number of elements - Include
<stack>and<queue>headers
Handle Container Exception Safety
In this step, you'll learn how to handle exceptions and ensure safe operations with STL containers. Exception handling helps prevent program crashes and provides robust error management.
Open the WebIDE and create a new file called exception_safety_demo.cpp in the ~/project directory:
touch ~/project/exception_safety_demo.cpp
Add the following code to the exception_safety_demo.cpp file:
#include <iostream>
#include <vector>
#include <stdexcept>
void demonstrateVectorSafety() {
std::vector<int> numbers;
try {
// Attempt to access an element from an empty vector
std::cout << "Attempting to access element from empty vector:" << std::endl;
numbers.at(0); // This will throw an out_of_range exception
}
catch (const std::out_of_range& e) {
std::cout << "Out of Range Error: " << e.what() << std::endl;
}
// Safe element addition
try {
numbers.push_back(10);
numbers.push_back(20);
std::cout << "Vector size: " << numbers.size() << std::endl;
// Safe element access
std::cout << "First element: " << numbers.at(0) << std::endl;
std::cout << "Second element: " << numbers.at(1) << std::endl;
}
catch (const std::exception& e) {
std::cout << "An error occurred: " << e.what() << std::endl;
}
}
int main() {
// Demonstrate vector exception safety
demonstrateVectorSafety();
return 0;
}
Compile and run the program:
g++ exception_safety_demo.cpp -o exception_safety_demo
./exception_safety_demo
Example output:
Attempting to access element from empty vector:
Out of Range Error: vector
Vector size: 2
First element: 10
Second element: 20
Key points about container exception safety:
- Use
try-catchblocks to handle potential exceptions std::out_of_rangeis thrown when accessing invalid vector elementsat()method performs bounds checking, unlike[]operator- Catch specific exceptions first, then more general ones
- Always handle potential exceptions to prevent program crashes
- Use standard exception classes from
<stdexcept>
Summary
In this lab, you learned about various components of the C++ Standard Template Library (STL) and how to use them effectively. You started by exploring the vector container, which is a dynamic array that can grow and shrink in size. You learned how to add and remove elements, access them using indices, and iterate through the vector using a range-based for loop.
Next, you delved into the list container, which is a doubly-linked list implementation. You discovered how to perform common linked list operations such as inserting, deleting, and traversing elements. You also explored the map container, which allows you to store key-value pairs, and the set container, which stores unique elements. Additionally, you learned how to use STL algorithms like sort and find to manipulate and search elements within these containers. Finally, you explored the stack and queue containers, and discussed the importance of exception safety when working with STL components.



