0% found this document useful (0 votes)
7 views31 pages

Containers

The document provides an introduction to C++ Standard Template Library (STL) containers, detailing various types such as sequence, associative, and unordered associative containers, along with container adapters. It includes practical examples of using different containers like vector, list, deque, set, map, and stack, demonstrating their functionalities through code snippets. Additionally, it covers operations such as adding, modifying, and removing elements, as well as sorting and searching within these containers.

Uploaded by

asite249
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views31 pages

Containers

The document provides an introduction to C++ Standard Template Library (STL) containers, detailing various types such as sequence, associative, and unordered associative containers, along with container adapters. It includes practical examples of using different containers like vector, list, deque, set, map, and stack, demonstrating their functionalities through code snippets. Additionally, it covers operations such as adding, modifying, and removing elements, as well as sorting and searching within these containers.

Uploaded by

asite249
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

PRACTICAL LESSON: CONTAINERS

(COLLECTIONS) IN C++
PART 1: INTRODUCTION TO STL CONTAINERS
What are Containers?

Containers are objects that store collections of other objects (elements). The C++ Standard
Template Library (STL) provides several container classes that implement various data
structures.

Types of Containers:

1.​ Sequence Containers: vector, deque, list, array, forward_list


2.​ Associative Containers: set, multiset, map, multimap
3.​ Unordered Associative Containers: unordered_set, unordered_map
4.​ Container Adapters: stack, queue, priority_queue

PART 2: SEQUENCE CONTAINERS


Example 1: Vector Container

cpp

#include <iostream>

#include <vector>

#include <algorithm>

using namespace std;

int main() {

cout << "VECTOR CONTAINER\n";

cout << "========================================\n\n";

// Creating a vector
vector<int> numbers;

// Adding elements

numbers.push_back(10);

numbers.push_back(20);

numbers.push_back(30);

numbers.push_back(40);

numbers.push_back(50);

cout << "Vector elements: ";

for(int i = 0; i < [Link](); i++) {

cout << numbers[i] << " ";

cout << endl;

// Using iterator

cout << "Using iterator: ";

for(vector<int>::iterator it = [Link](); it != [Link](); it++) {

cout << *it << " ";

cout << endl;

// Using range-based for loop

cout << "Using range-based loop: ";

for(int num : numbers) {

cout << num << " ";


}

cout << endl;

// Vector properties

cout << "\nVector Properties:\n";

cout << "Size: " << [Link]() << endl;

cout << "Capacity: " << [Link]() << endl;

cout << "First element: " << [Link]() << endl;

cout << "Last element: " << [Link]() << endl;

cout << "Element at index 2: " << [Link](2) << endl;

// Modifying elements

numbers[1] = 25;

cout << "\nAfter modification: ";

for(int num : numbers) {

cout << num << " ";

cout << endl;

// Removing elements

numbers.pop_back(); // Remove last element

cout << "After pop_back: ";

for(int num : numbers) {

cout << num << " ";

cout << endl;


// Inserting elements

[Link]([Link]() + 2, 100); // Insert at position 2

cout << "After insert at position 2: ";

for(int num : numbers) {

cout << num << " ";

cout << endl;

// Erasing elements

[Link]([Link]() + 1); // Erase element at position 1

cout << "After erase at position 1: ";

for(int num : numbers) {

cout << num << " ";

cout << endl;

// Sorting

sort([Link](), [Link]());

cout << "After sorting: ";

for(int num : numbers) {

cout << num << " ";

cout << endl;

// Clearing vector
[Link]();

cout << "After clear, size: " << [Link]() << endl;

return 0;

Example 2: Vector with Custom Objects

cpp

#include <iostream>

#include <vector>

#include <string>

#include <algorithm>

using namespace std;

class Student {

private:

string name;

int id;

float gpa;

public:

Student(string n, int i, float g) : name(n), id(i), gpa(g) {}

void display() const {

cout << "ID: " << id << ", Name: " << name << ", GPA: " << gpa << endl;

}
// Getters

string getName() const { return name; }

int getID() const { return id; }

float getGPA() const { return gpa; }

// Comparison operator for sorting

bool operator<(const Student& other) const {

return gpa > [Link]; // Sort by GPA descending

};

int main() {

cout << "VECTOR WITH CUSTOM OBJECTS\n";

cout << "========================================\n\n";

vector<Student> students;

// Adding students

students.push_back(Student("Alice Johnson", 101, 3.8));

students.push_back(Student("Bob Smith", 102, 3.5));

students.push_back(Student("Carol Davis", 103, 3.9));

students.push_back(Student("David Lee", 104, 3.6));

students.push_back(Student("Emma Wilson", 105, 3.95));

cout << "Original list:\n";


for(const Student& s : students) {

[Link]();

// Sort by GPA

sort([Link](), [Link]());

cout << "\nSorted by GPA (highest to lowest):\n";

for(const Student& s : students) {

[Link]();

// Find student by ID

int searchID = 103;

cout << "\nSearching for student with ID " << searchID << ":\n";

for(const Student& s : students) {

if([Link]() == searchID) {

[Link]();

break;

return 0;

Example 3: List Container


cpp

#include <iostream>

#include <list>

using namespace std;

int main() {

cout << "LIST CONTAINER (DOUBLY LINKED LIST)\n";

cout << "========================================\n\n";

list<int> myList;

// Adding elements

myList.push_back(10);

myList.push_back(20);

myList.push_back(30);

myList.push_front(5); // Add to front

myList.push_front(1);

cout << "List elements: ";

for(int num : myList) {

cout << num << " ";

cout << endl;

// List operations

cout << "Size: " << [Link]() << endl;


cout << "Front: " << [Link]() << endl;

cout << "Back: " << [Link]() << endl;

// Removing elements

myList.pop_front();

myList.pop_back();

cout << "\nAfter pop_front and pop_back: ";

for(int num : myList) {

cout << num << " ";

cout << endl;

// Sorting list

[Link]();

cout << "After sorting: ";

for(int num : myList) {

cout << num << " ";

cout << endl;

// Reversing list

[Link]();

cout << "After reversing: ";

for(int num : myList) {

cout << num << " ";


}

cout << endl;

// Removing specific value

[Link](10);

cout << "After removing 10: ";

for(int num : myList) {

cout << num << " ";

cout << endl;

return 0;

Example 4: Deque Container

cpp

#include <iostream>

#include <deque>

using namespace std;

int main() {

cout << "DEQUE CONTAINER (DOUBLE-ENDED QUEUE)\n";

cout << "========================================\n\n";

deque<int> dq;
// Adding elements

dq.push_back(10);

dq.push_back(20);

dq.push_back(30);

dq.push_front(5);

dq.push_front(1);

cout << "Deque elements: ";

for(int num : dq) {

cout << num << " ";

cout << endl;

// Access elements

cout << "Front: " << [Link]() << endl;

cout << "Back: " << [Link]() << endl;

cout << "Element at index 2: " << dq[2] << endl;

// Insert at specific position

[Link]([Link]() + 2, 100);

cout << "\nAfter insert at position 2: ";

for(int num : dq) {

cout << num << " ";

cout << endl;


// Remove from both ends

dq.pop_front();

dq.pop_back();

cout << "After pop_front and pop_back: ";

for(int num : dq) {

cout << num << " ";

cout << endl;

return 0;

PART 3: ASSOCIATIVE CONTAINERS


Example 5: Set Container

cpp

#include <iostream>

#include <set>

using namespace std;

int main() {

cout << "SET CONTAINER (UNIQUE SORTED ELEMENTS)\n";

cout << "========================================\n\n";

set<int> mySet;

// Inserting elements (automatically sorted and unique)


[Link](50);

[Link](20);

[Link](40);

[Link](10);

[Link](30);

[Link](20); // Duplicate - will not be inserted

cout << "Set elements (automatically sorted): ";

for(int num : mySet) {

cout << num << " ";

cout << endl;

cout << "Size: " << [Link]() << endl;

// Finding element

int searchValue = 30;

if([Link](searchValue) != [Link]()) {

cout << searchValue << " found in set" << endl;

} else {

cout << searchValue << " not found in set" << endl;

// Counting occurrences (always 0 or 1 in set)

cout << "Count of 20: " << [Link](20) << endl;

cout << "Count of 100: " << [Link](100) << endl;


// Erasing element

[Link](30);

cout << "\nAfter erasing 30: ";

for(int num : mySet) {

cout << num << " ";

cout << endl;

// Lower and upper bound

auto it = mySet.lower_bound(25);

if(it != [Link]()) {

cout << "Lower bound of 25: " << *it << endl;

return 0;

Example 6: Map Container

cpp

#include <iostream>

#include <map>

#include <string>

using namespace std;

int main() {
cout << "MAP CONTAINER (KEY-VALUE PAIRS)\n";

cout << "========================================\n\n";

// Creating a map (student ID -> name)

map<int, string> students;

// Inserting elements

students[101] = "Alice Johnson";

students[102] = "Bob Smith";

students[103] = "Carol Davis";

[Link](make_pair(104, "David Lee"));

[Link](pair<int, string>(105, "Emma Wilson"));

// Displaying all elements

cout << "Student Database:\n";

for(auto pair : students) {

cout << "ID: " << [Link] << ", Name: " << [Link] << endl;

// Accessing elements

cout << "\nStudent with ID 103: " << students[103] << endl;

// Finding element

int searchID = 102;

auto it = [Link](searchID);

if(it != [Link]()) {
cout << "Found - ID: " << it->first << ", Name: " << it->second << endl;

// Checking if key exists

if([Link](104)) {

cout << "ID 104 exists in database" << endl;

// Modifying value

students[101] = "Alice Smith"; // Changed name

// Removing element

[Link](105);

cout << "\nUpdated Student Database:\n";

for(const auto& pair : students) {

cout << "ID: " << [Link] << ", Name: " << [Link] << endl;

cout << "\nMap size: " << [Link]() << endl;

return 0;

Example 7: Advanced Map Usage

cpp
#include <iostream>

#include <map>

#include <string>

using namespace std;

class Product {

public:

string name;

double price;

int quantity;

Product(string n = "", double p = 0.0, int q = 0)

: name(n), price(p), quantity(q) {}

void display() const {

cout << "Product: " << name

<< ", Price: $" << price

<< ", Quantity: " << quantity << endl;

};

int main() {

cout << "MAP WITH CUSTOM OBJECTS\n";

cout << "========================================\n\n";

map<int, Product> inventory;


// Adding products

inventory[1001] = Product("Laptop", 899.99, 15);

inventory[1002] = Product("Smartphone", 599.99, 25);

inventory[1003] = Product("Tablet", 399.99, 20);

inventory[1004] = Product("Headphones", 149.99, 50);

inventory[1005] = Product("Smartwatch", 299.99, 30);

cout << "INVENTORY SYSTEM:\n";

cout << "----------------------------------------\n";

for(const auto& item : inventory) {

cout << "Code: " << [Link] << " - ";

[Link]();

// Search for product

int productCode = 1003;

cout << "\nSearching for product code " << productCode << ":\n";

if([Link](productCode) != [Link]()) {

inventory[productCode].display();

// Update product quantity

inventory[1002].quantity += 10;

cout << "\nAfter restocking product 1002:\n";

inventory[1002].display();
// Calculate total inventory value

double totalValue = 0;

for(const auto& item : inventory) {

totalValue += [Link] * [Link];

cout << "\nTotal Inventory Value: $" << totalValue << endl;

return 0;

PART 4: CONTAINER ADAPTERS


Example 8: Stack Container Adapter

cpp

#include <iostream>

#include <stack>

#include <string>

using namespace std;

int main() {

cout << "STACK CONTAINER ADAPTER (LIFO)\n";

cout << "========================================\n\n";

stack<int> myStack;

// Pushing elements
cout << "Pushing elements: 10, 20, 30, 40, 50\n";

[Link](10);

[Link](20);

[Link](30);

[Link](40);

[Link](50);

cout << "Stack size: " << [Link]() << endl;

cout << "Top element: " << [Link]() << endl;

// Popping elements

cout << "\nPopping all elements:\n";

while(![Link]()) {

cout << [Link]() << " ";

[Link]();

cout << endl;

// Practical example: Reverse a string

cout << "\nREVERSING STRING USING STACK:\n";

string text = "Hello World";

stack<char> charStack;

cout << "Original: " << text << endl;

// Push all characters


for(char c : text) {

[Link](c);

// Pop to get reversed string

cout << "Reversed: ";

while(![Link]()) {

cout << [Link]();

[Link]();

cout << endl;

return 0;

Example 9: Queue Container Adapter

cpp

#include <iostream>

#include <queue>

#include <string>

using namespace std;

int main() {

cout << "QUEUE CONTAINER ADAPTER (FIFO)\n";

cout << "========================================\n\n";


queue<string> customerQueue;

// Adding customers to queue

cout << "Customers arriving:\n";

[Link]("Alice");

cout << "Alice joined the queue\n";

[Link]("Bob");

cout << "Bob joined the queue\n";

[Link]("Carol");

cout << "Carol joined the queue\n";

[Link]("David");

cout << "David joined the queue\n";

cout << "\nQueue size: " << [Link]() << endl;

cout << "Front of queue: " << [Link]() << endl;

cout << "Back of queue: " << [Link]() << endl;

// Serving customers

cout << "\nServing customers:\n";

while(![Link]()) {

cout << "Serving: " << [Link]() << endl;

[Link]();

return 0;

}
Example 10: Priority Queue

cpp

#include <iostream>

#include <queue>

#include <string>

using namespace std;

class Task {

public:

string name;

int priority;

Task(string n, int p) : name(n), priority(p) {}

// Operator for priority comparison

bool operator<(const Task& other) const {

return priority < [Link]; // Higher priority first

};

int main() {

cout << "PRIORITY QUEUE (HIGHEST PRIORITY FIRST)\n";

cout << "========================================\n\n";

// Simple priority queue with integers


priority_queue<int> pq;

[Link](30);

[Link](10);

[Link](50);

[Link](20);

[Link](40);

cout << "Priority Queue (integers - highest first):\n";

while(![Link]()) {

cout << [Link]() << " ";

[Link]();

cout << endl;

// Priority queue with custom objects

cout << "\nTASK MANAGEMENT SYSTEM:\n";

cout << "----------------------------------------\n";

priority_queue<Task> taskQueue;

[Link](Task("Write report", 3));

[Link](Task("Fix critical bug", 5));

[Link](Task("Email response", 2));

[Link](Task("Team meeting", 4));

[Link](Task("Code review", 3));


cout << "Tasks in priority order:\n";

while(![Link]()) {

Task currentTask = [Link]();

cout << "Priority " << [Link]

<< ": " << [Link] << endl;

[Link]();

return 0;

PART 5: UNORDERED CONTAINERS


Example 11: Unordered Map

cpp

#include <iostream>

#include <unordered_map>

#include <string>

using namespace std;

int main() {

cout << "UNORDERED MAP (HASH TABLE)\n";

cout << "========================================\n\n";

unordered_map<string, int> wordCount;


// Counting word frequencies

string text[] = {"apple", "banana", "apple", "cherry",

"banana", "apple", "date", "banana"};

for(string word : text) {

wordCount[word]++;

cout << "Word Frequencies:\n";

for(const auto& pair : wordCount) {

cout << [Link] << ": " << [Link] << endl;

// Phone book example

cout << "\nPHONE BOOK:\n";

cout << "----------------------------------------\n";

unordered_map<string, string> phoneBook;

phoneBook["Alice"] = "+1-555-1234";

phoneBook["Bob"] = "+1-555-5678";

phoneBook["Carol"] = "+1-555-9012";

phoneBook["David"] = "+1-555-3456";

// Lookup

string name = "Carol";


if([Link](name) != [Link]()) {

cout << name << "'s phone: " << phoneBook[name] << endl;

// Display all contacts

cout << "\nAll contacts:\n";

for(const auto& contact : phoneBook) {

cout << [Link] << ": " << [Link] << endl;

return 0;

PART 6: PRACTICAL APPLICATIONS


Example 12: Student Management System

cpp

#include <iostream>

#include <vector>

#include <map>

#include <string>

#include <algorithm>

using namespace std;

class Student {

public:

int id;
string name;

vector<int> grades;

Student(int i, string n) : id(i), name(n) {}

void addGrade(int grade) {

grades.push_back(grade);

double getAverage() const {

if([Link]()) return 0.0;

int sum = 0;

for(int grade : grades) {

sum += grade;

return static_cast<double>(sum) / [Link]();

void display() const {

cout << "ID: " << id << ", Name: " << name;

cout << ", Average: " << getAverage() << endl;

};

int main() {

cout << "STUDENT MANAGEMENT SYSTEM\n";


cout << "========================================\n\n";

map<int, Student> students;

// Adding students

[Link](make_pair(101, Student(101, "Alice Johnson")));

[Link](make_pair(102, Student(102, "Bob Smith")));

[Link](make_pair(103, Student(103, "Carol Davis")));

// Adding grades

students[101].addGrade(85);

students[101].addGrade(90);

students[101].addGrade(88);

students[102].addGrade(92);

students[102].addGrade(87);

students[102].addGrade(95);

students[103].addGrade(78);

students[103].addGrade(82);

students[103].addGrade(80);

// Display all students

cout << "ALL STUDENTS:\n";

for(const auto& pair : students) {

[Link]();
}

// Find top student

int topID = 101;

double maxAvg = students[101].getAverage();

for(const auto& pair : students) {

if([Link]() > maxAvg) {

maxAvg = [Link]();

topID = [Link];

cout << "\nTOP STUDENT:\n";

students[topID].display();

return 0;

PART 7: PRACTICE EXERCISES


Exercise 1: Library Management

Create a library system using map to store books (ISBN -> Book details). Implement search,
add, remove, and list all books functions.

Exercise 2: Shopping Cart

Use vector to store items in a shopping cart. Implement add item, remove item, calculate
total, and apply discount functions.
Exercise 3: Contact Management

Create a contact management system using unordered_map with name as key and phone
number as value. Add search, update, delete features.

Exercise 4: Task Scheduler

Implement a task scheduler using priority_queue where tasks are sorted by deadline and
priority.

Exercise 5: Inventory System

Create an inventory system using multiple containers: map for products, vector for sales
history, and set for unique categories.

You might also like