0% found this document useful (0 votes)
123 views

Oop PPT (STL)

The document provides an overview of the Standard Template Library (STL) in C++. It discusses the main components of STL including containers, iterators, and algorithms. It describes common sequence containers like vectors and lists, and associative containers like sets and maps. It provides examples of using STL vectors and lists and their basic functions and syntax.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
123 views

Oop PPT (STL)

The document provides an overview of the Standard Template Library (STL) in C++. It discusses the main components of STL including containers, iterators, and algorithms. It describes common sequence containers like vectors and lists, and associative containers like sets and maps. It provides examples of using STL vectors and lists and their basic functions and syntax.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 30

Standard Template Library (STL)

by Ojas Jain 21435


Aastha Shah 21449
Niranjan Dangi 21458
Pankaj Ahirrao 21475
Madhura Pawar 21492
Contents
Introduction to STL
Containers

Sequence Containers

Associative Containers

STL Vectors

STL Lists

Assignment related to STL


Pre-requisites
What is Generic Programming?
Generic Programming enables the programmer to write a general algorithm which will work with all data types. It
eliminates the need to create different algorithms if the data type is an integer, string or a character. Generics can
be implemented in C++ using Templates.

What are the advantages of Generic Programming?


1.Code Reusability
2.Avoid Function Overloading
3.Once written it can be used for multiple times and cases.
Introduction to STL
• The Standard Template Library (STL) is a set of C++ template classes to provide common programming data structures and
functions such as lists, stacks, arrays, etc. It is a library of container classes, algorithms, and iterators.

• Following are the components of STL:

 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.

Following are the features of Sequence Containers:

 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 .

Following are the features of Sequence Containers:

 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;

 multiset: Similar to set, but allows duplicate keys.


Syntax: multiset<int> myMultiSet;

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;

 multimap: Similar to map, but allows duplicate keys.


Syntax: multimap<string, int> myMultimap;
Example for set: Example for Map:

#include <iostream> #include <iostream>


#include <set> #include <map>
using namespace std; Using namespace std;
int main()
int main() {
{ map<string, int> myMap;
set<int> mySet;
// Inserting elements into the map
mySet.insert(10); myMap["Alice"] = 25;
mySet.insert(5); myMap["Bob"] = 30;
mySet.insert(20); myMap["Charlie"] = 22;
mySet.insert(15);
// Accessing elements using keys
cout << "Elements in the set: "; cout << "Age of Bob: " << myMap["Bob"] << endl;
for (const auto& elem : mySet)
{ return 0;
cout << elem << " "; }
}
cout << endl; Output: Elements in the map:
Alice: 22
return 0; Bob: 30
} Charlie: 22
Age of Bob: 30
Output : Elements in the set: 5 10 15 20
STL Vectors

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.

Features of STL Vectors:

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;

For Example: std::vector<int> myvector;

To initialize some values: std::vector<int> myvector{x, y, z};

To add elements: myvector.push_back(5)

To access elements: myvector[0];


myvector.at(2);
Functions in Vectors:

i) begin() x) back()

ii) end() xi) at()

iii) size() xii) data()

iv) max_size() xiii)push_back()

v) resize() xiv)pop_back()

vi) capacity() xv) insert()

vii) empty() xvi)swap()

viii)reserve() xvii) clear()

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.

Basic Characteristics of Lists:


1. Dynamic Size:
Lists can dynamically grow or shrink as elements are added or removed.
2. Efficient Insertion and Deletion:
Operations like push_back, push_front, insert, pop_back, and pop_front have constant-time complexity.
3. Bidirectional Traversal:
Lists support bidirectional iterators, allowing traversal in both forward and backward directions
STL Lists
Creating and Initializing Lists:
To use lists, include the <list> header:

Declaration and Initialization:


STL Lists
Basic Operations on Lists
Insertion and Deletion:
STL Lists
List Functions and Methods:

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.

#include <iostream> // Simulate printing the current state of the document


#include <stack> stack<string> tempStack = commandHistory;
#include <string> while (!tempStack.empty()) {
using namespace std; cout << tempStack.top() << endl;
tempStack.pop();
int main() { }
// Create a stack to store the history of commands
stack<string> commandHistory; cout << "-----------------------" << endl;

// 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();
}

cout << "--------------------------" << endl;

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:

• push(g) : Adds the element ‘g’ at the end of the queue.

• pop() : Deletes the first element of the queue.

• front() : Returns a reference to the first element of the queue.

• 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; 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; }

cout << "Enter Name of Item: "; static void search()


cin >> obj.name; {
int searchCode;
cout << "Enter Price of Item: "; cout << "\nEnter Item Code to search: ";
cin >> obj.price; cin >> searchCode;

cout << "Enter Quantity of Item: "; bool found = false;


cin >> obj.qty;

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; }

case 2: } while (ch != 6);


Item::display();
break; return 0;
}
case 3:
object.search();
break;
Output:
case 4:
sort(Item::o1.begin(), Item::o1.end(), 1.Insert:
Item::comparePrice);
cout << "\nSorted on Price:";
Item::display();
break;
* * * * * Menu * * * * * Item Name : Cars
1.Insert Item Quantity : 2
2.Display Item Cost : 4000
3.Search Item Code : 102
4.Sort
5.Delete 3.Search:
6.Exit Enter your choice : 3
Enter Item Code to search : 101
Enter your choice : 1 Found!!!
Enter Item Name : Toys
Enter Item Quantity : 2 4.Sort:
Enter Item Cost : 5000 Sorted on Cost :
Enter Item Code : 101 Item Name : Cars
Item Quantity : 2
Enter your choice : 1 Item Cost : 4000
Enter Item Name : Cars Item Code : 102
Enter Item Quantity : 2 Item Name : Toys
Enter Item Cost : 4000 Item Quantity : 2
Enter Item Code : 102 Item Cost : 5000
Item Code : 101
2.Display: 5.Delete:
Enter your choice : 5
Enter your choice : 2 Enter Item Code to delete : 101
Item Name : Toys Deleted!!!
Item Quantity : 2 Enter your choice : 2
Item Cost : 5000 Item Name : Cars
Item Code : 101 Item Quantity : 2
Item Cost : 4000
Item Code : 102

You might also like