Oop PPT (STL)
Oop PPT (STL)
Sequence Containers
Associative Containers
STL Vectors
STL Lists
Containers: A container is a collection of objects of different types which is used to store data.It can be implemented with the
help of templates.
Iterators: These are pointers which are used to traverse the contents of the container.
Algorithm: These are used to process the contents of the container.Complex operations can be performed with the help of
algorithms.
Containers
Sequence Containers
They provide a way to store elements in a particular order.
They are implemented as dynamic arrays, linked lists, and arrays of fixed-size elements.
These containers provide several functions to manipulate the elements, such as accessing elements, inserting and
deleting elements, and searching for elements.
Ordered Storage: Can store elements in a particular order, defined by their position in the container. This makes it
possible to insert and remove elements at any point while also enabling effective random access to elements.
Random Access: Can access any element in the container directly without having to traverse through the entire
container.
Dynamic Size: Sequence Containers can have their size changed at any moment, allowing you to add or remove items
as needed.
Efficient Insertion and Deletion: Efficient insertion and deletion of elements at any position in the container.
Standardized Interface: Can use the same set of functions to manipulate elements, regardless of the type of sequence
container being used.
.
Container Adapters
Container adapters in C++ are special types of containers that provide a restricted interface to the underlying
container class. They adapt the interface of the underlying container to support a specific behavior or use case .
The three main container adapters in C++ are std::stack, std::queue, and std::priority_queue. Here are some
features common to container adapters:
1.Specialized Functionality:
•Each container adapter is designed for a specific purpose.
•stack for Last-In-First-Out (LIFO) behavior.
•queue for First-In-First-Out (FIFO) behavior.
•priority_queue for managing elements with priorities.
2.Limited Interface:
•Container adapters expose a restricted set of operations, focusing on functionality specific to the adapter's
purpose.
•This restriction makes the interface cleaner and more intuitive for certain use cases.
3.Underlying Container:
•Container adapters use an underlying container to store elements.
•You can often specify the underlying container type, allowing some flexibility in choosing the appropriate
container for your needs.
Associate Containers
In C++, associative containers are part of the Standard Template Library (STL) and provide a way to store and retrieve elements
using keys rather than indices.
Unlike sequential containers like vectors or lists, associative containers do not have a strict order of elements, and the order is
determined by the keys.
A "key" refers to the part of the container's element that is used for ordering or indexing. In key-based containers like set, map, etc.,
each element in the container is associated with a key
For set and map,
In std::set, the key is the element itself
In std::map, each element is a key-value pair, and the key is used for ordering .
Key-Value Storage: Elements in associative containers are stored as key-value pairs. Each element has a unique key associated
with it.
Ordered or Unordered: Depending on the type of associative container, elements may be stored in an ordered (sorted) or
unordered manner.set and map are ordered containers where elements are sorted by keys. unordered_set and unordered_map are
unordered containers where the order of elements is not guaranteed.
Fast Lookup: Associative containers are designed for fast lookup based on keys. Searching for an element by its key has an
average time complexity of O(log n) for ordered containers and O(1) for unordered containers.
And Dynamic size, efficient Insertion and Deletion etc
There are several associative containers in C++, and they can be broadly categorized into two types: std::set-based and
std::map-based.
1.Set-Based Containers:
set: It is an ordered collection of unique keys. The elements are always sorted in ascending order.
Syntax: set<int> mySet;
2.Map-Based Containers:
map: A collection of key-value pairs where each key is unique. The elements are sorted based on the keys.
Syntax: map<string, int> myMap;
STL vectors are a part of the C++ Standard Library and provide a dynamic array implementation. They
are one of the most used data structures in C++ due to their flexibility and efficiency.
i) Dynamic Resizing: They are sequence container used to represent array which can change size i.e.
elements can be added/deleted without memory management problems.
ii) Contiguous Memory: Elements in vectors are stored in memory locations which have the same
borders or are adjacent/near each other.
iii) Template Class: Vectors are implemented as a template class, allowing you to create vectors of
any data type.
STL Vectors
Basic Syntax of STL Vectors:
#include <vector>
std::vector<DataType> name;
i) begin() x) back()
v) resize() xiv)pop_back()
ix) front()
Output:
STL Lists
Introduction to Lists:
In C++, the Standard Template Library (STL) provides a powerful set of container classes and algorithms to
simplify programming tasks. One of the key container classes is the list. A list is a doubly-linked list
implementation that allows efficient insertion and deletion operations at any position within the list.
Common member functions of the List class include empty(), size(), front(), back(), and clear():
Stack: It is a Last-In-First-Out (LIFO) data structure, where the last element added is the first one to be removed.By default, it is
implemented on top of std::deque (double-ended queue), but you can also specify other containers like std::vector or std::list.
Common Operations:
•push(): Adds an element to the top of the stack.
•pop(): Removes the top element from the stack.
•top(): Returns a reference to the top element without removing it.
// Simulate user input and execute commands // User decides to undo the last command
commandHistory.push("Open Document"); if (!commandHistory.empty()) {
commandHistory.push("Write Introduction"); cout << "Undoing the last command: " <<
commandHistory.push("Format Text"); commandHistory.top() << endl;
commandHistory.pop();
// Print the current state of the document }
cout << "Current Document State:" << endl; // Print the updated document state after undo
cout << "-----------------------" << endl; cout << "Document State after Undo:" << endl;
cout << "--------------------------" << endl;
// Simulate printing the updated state
while (!commandHistory.empty()) {
cout << commandHistory.top() << endl;
commandHistory.pop();
}
return 0;
}
Output:
Current Document State:
-----------------------
Format Text
Write Introduction
Open Document
-----------------------
Undoing the last command: Format Text
Document State after Undo:
--------------------------
Write Introduction
Open Document
--------------------------
Queue:- Queues are a type of container adaptors that operate in a first in first out (FIFO) type of arrangement. Elements are
inserted at the back (end) and are deleted from the front. Queues use an encapsulated object of deque or list (sequential container
class) as its underlying container, providing a specific set of member functions to access its elements.
Common Operations:
• empty() : Returns whether the queue is empty. It return true if the queue is empty otherwise returns false.
// Driver Code
int main() // Driver Code
#include <iostream> int main()
#include #include
<iostream> {
<queue> { q1;
queue<int>
#include <queue>
q1.push(1);queue<int> q1;
using namespace std; q1.push(2);q1.push(1);
using namespace std; q1.push(3);q1.push(2);
// Print the queue q1.push(3);
// Print void
the print_queue(queue<int>
queue q) cout << "The first queue is : ";
void print_queue(queue<int>
{ q) print_queue(q1);
cout << "The first queue is : ";
{ queue<int> temp = q;
queue<int> temp = q; queue<int>print_queue(q1);
q2;
while (!temp.empty()) { q2.push(4);
while (!temp.empty()) {
cout << temp.front()<<" "; q2.push(5); queue<int> q2;
couttemp.pop();
<< temp.front()<<" "; q2.push(6);q2.push(4);
temp.pop();
} q2.push(5);
} cout << '\n'; cout << "The second queue is : ";
q2.push(6);
cout }<< '\n'; print_queue(q2);
}
cout << "The second queue is : ";
q1.swap(q2);
} print_queue(q2);
}
q1.swap(q2);
cout << "After swapping, the first queue is : ";
cout << "After swapping, the first queue is : ";
print_queue(q1);
cout << "After swapping the second queue is : ";
print_queue(q1);
print_queue(q2);
cout << "After swapping the second queue is : ";
print_queue(q2);
cout<<q1.empty(); //returns false since q1 is not empty
return 0;
}
Output:
The first queue is : 1 2 3
The second queue is : 4 5 6
After swapping, the first queue is : 4 5 6
After swapping the second queue is : 1 2 3 0
Assignment related to STL
Problem Statement :-
Assignment No 6
Write C++ program using STL for sorting and searching user-defined records
such as Item records (Item code, name, cost, quantity, etc) using vector
container.
#include <iostream> static void print(const Item &i1)
#include <vector> {
#include <algorithm> cout << "\nItem Code : " << i1.code;
using namespace std; cout << "\nItem Name : " << i1.name;
class Item cout << "\nItem Cost : " << i1.price;
{ cout << "\nItem Quantity: " << i1.qty << endl;
private: }
int code;
string name; static void display()
int price; {
int qty; for_each(o1.begin(), o1.end(), print);
public: }
static vector<Item> o1;
static void insert() static bool comparePrice(const Item &a, const
{ Item &b)
Item obj; {
cout << "Enter Code of Item: "; return a.price < b.price;
cin >> obj.code; }
o1.push_back(obj);
}
for (const auto &item : o1)
for (auto it = o1.begin(); it != o1.end(); ++it)
{
{
if (item.code == searchCode)
if (it->code == deleteCode)
{
{
cout << "Item found!";
o1.erase(it);
item.print(item);
cout << "Item deleted!";
found = true;
deleted = true;
break;
break;
}
}
}
}
if (!found)
if (!deleted)
{
{
cout << "Item not found!";
cout << "Item not found!";
}
}
}
}
static void dlt()
};
{
vector<Item> Item::o1;
int deleteCode;
cout << "\nEnter Item Code to delete: ";
int main()
cin >> deleteCode;
{
Item object;
bool deleted = false;
int ch;
do
{
cout << "\n* * * * * Menu * * * * *";
cout << "\n1. Insert"; case 5:
cout << "\n2. Display"; object.dlt();
cout << "\n3. Search"; break;
cout << "\n4. Sort";
cout << "\n5. Delete"; case 6:
cout << "\n6. Exit"; cout << "Exiting program." << endl;
cout << "\nEnter your choice: "; break;
cin >> ch;
switch (ch) default:
{ cout << "Invalid choice! Please enter a valid
case 1: option." << endl;
object.insert(); break;
break; }