0% found this document useful (0 votes)
2 views21 pages

STL_Notes

The document provides an overview of the Standard Template Library (STL) in C++, detailing its components including containers, iterators, algorithms, and function objects (functors). It explains the benefits of using STL, such as saving development time and reducing bugs, and includes examples demonstrating the use of various STL components. The document also categorizes different types of containers and algorithms, emphasizing their flexibility and reusability.

Uploaded by

dikshakarna696
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)
2 views21 pages

STL_Notes

The document provides an overview of the Standard Template Library (STL) in C++, detailing its components including containers, iterators, algorithms, and function objects (functors). It explains the benefits of using STL, such as saving development time and reducing bugs, and includes examples demonstrating the use of various STL components. The document also categorizes different types of containers and algorithms, emphasizing their flexibility and reusability.

Uploaded by

dikshakarna696
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

Unit 8

Standard Template Library (STL) in C++


Topics covered
8.5 Introduction to Standard Template Library
8.5.1 Components of STL
8.5.2 Container
8.5.3 Iterators
8.5.4 Algorithms
Table of Contents
Table of Contents .......................................................................................................................................... 2
8.5 Introduction to Standard Template Library (STL) .................................................................................. 3
8.5.1 Components of STL ............................................................................................................................. 5
1. Containers ......................................................................................................................................... 5
2. Algorithms ......................................................................................................................................... 5
3. Iterators............................................................................................................................................. 5
4. Function Objects (Functors) .............................................................................................................. 5
8.5.2 Container............................................................................................................................................. 7
A. Sequence Containers ............................................................................................................................ 7
1. vector ................................................................................................................................................ 7
2. list ...................................................................................................................................................... 8
3. deque ................................................................................................................................................ 8
B. Associative Containers ........................................................................................................................ 10
1. set.................................................................................................................................................... 10
2. map ................................................................................................................................................. 10
C. Container Adapters ............................................................................................................................. 12
1. stack ................................................................................................................................................ 12
2. queue .............................................................................................................................................. 12
3. priority_queue ................................................................................................................................ 13
8.5.3 Iterators............................................................................................................................................. 14
Categories of Iterators ............................................................................................................................ 14
8.5.4 Algorithms ......................................................................................................................................... 17
Categories of Algorithms ........................................................................................................................ 17
Summary ..................................................................................................................................................... 21
Review Questions........................................................................................................................................ 21

(Right-click the table above and choose “Update Field” after opening in Word to populate page numbers.)
8.5 Introduction to Standard Template Library (STL)
The Standard Template Library (STL) is a powerful set of C++ template classes and functions that provide
general-purpose, reusable, and efficient implementations of common data structures and algorithms.
Instead of writing code for linked lists, stacks, searching, or sorting from scratch, a programmer can
simply use the ready-made, well-tested components supplied by the STL.

STL is part of the C++ Standard Library and is built entirely using templates, which makes it type-
independent — the same container or algorithm can work with integers, floating-point numbers, strings,
or user-defined objects without rewriting the code.

Definition
The Standard Template Library (STL) is a collection of generic classes and functions in C++ that
implements commonly used data structures (containers) and algorithms (searching, sorting, etc.)
using the concept of templates and iterators.

Why STL is used:


● Saves development time — ready-made, tested code for common tasks.
● Generic and reusable — works with any data type through templates.
● Efficient — implemented with optimized algorithms and data structures.
● Reduces bugs — no need to re-implement standard data structures.
● Encourages consistent, readable, and maintainable code.

A minimal example that uses STL components together:

Program 1: A first look at STL (vector + iterator + algorithm)

#include <iostream>
#include <vector> // STL container
#include <algorithm> // STL algorithm

using namespace std;

int main() {
vector<int> numbers = {40, 10, 30, 20}; // container

sort([Link](), [Link]()); // algorithm + iterators

cout << "Sorted numbers: ";


for (vector<int>::iterator it = [Link](); it != [Link](); ++it)
cout << *it << " "; // iterator dereferencing
cout << endl;

return 0;
}
Output

Sorted numbers: 10 20 30 40

Notice how three STL pieces cooperate in the program above: the vector (container) stores data, the
iterator (begin()/end()) moves through the data, and sort() (algorithm) processes the data.
8.5.1 Components of STL
The STL is broadly organized into four major components that work together:

Component Description

Containers Objects that store collections of data (e.g., vector, list, set, map).
Functions that perform operations on data held in containers (e.g., sort,
Algorithms
search, copy).
Objects that act like pointers, used to traverse the elements of a
Iterators
container.
Objects that behave like functions; used to customize algorithm
Function Objects (Functors)
behaviour (e.g., comparators).

1. Containers
Containers are objects that hold a collection of other objects (elements). STL provides three categories
of containers: sequence containers (vector, list, deque, array), associative containers (set, map, multiset,
multimap), and container adapters (stack, queue, priority_queue). These are discussed in detail in
Section 8.5.2.

2. Algorithms
Algorithms are independent, generic functions (such as sort(), find(), reverse(), count()) that operate on
ranges of elements specified by iterators, rather than on a specific container type. Because of this, the
same algorithm works on a vector, a list, or even a plain array. Discussed in detail in Section 8.5.4.

3. Iterators
Iterators are objects (similar to pointers) that point to elements inside a container and allow algorithms
to move through (traverse) those elements without needing to know the internal structure of the
container. Discussed in detail in Section 8.5.3.

4. Function Objects (Functors)


A functor is an object of a class that overloads operator(), so it can be called and used like a function. STL
algorithms often accept functors (or lambda expressions) to customize their behaviour, for example, to
sort in descending order instead of ascending order.

Program 2: A simple functor used with the sort() algorithm

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

class Descending { // a functor class


public:
bool operator()(int a, int b) {
return a > b; // descending order rule
}
};

int main() {
vector<int> v = {5, 1, 4, 2, 3};

sort([Link](), [Link](), Descending()); // functor passed to algorithm

for (int x : v) cout << x << " ";


cout << endl;
return 0;
}

Output

5 4 3 2 1

Key Point
Containers store data, iterators traverse data, algorithms process data, and functors customize how
algorithms behave — together these four components make STL flexible and generic.
8.5.2 Container
A container is an STL class template that stores a collection of objects of the same type. Containers
manage the memory used by the elements they store and provide member functions to access and
manipulate them. STL containers are divided into three categories:

Category Containers Description

Sequence Containers vector, list, deque, array Store elements in a linear, ordered sequence.
Associative Containers set, multiset, map, multimap Store elements in sorted order, keyed for fast lookup.
Restrict the interface of an underlying container to
Container Adapters stack, queue, priority_queue
give special behaviour.

A. Sequence Containers

1. vector
A vector is a dynamic array that can grow or shrink in size automatically. It allows fast random access
using the [] operator and fast insertion/removal at the end.

Program 3: Demonstrating vector

#include <iostream>
#include <vector>
using namespace std;

int main() {
vector<int> v; // empty vector

v.push_back(10);
v.push_back(20);
v.push_back(30);

cout << "Vector elements: ";


for (int i = 0; i < [Link](); i++)
cout << v[i] << " ";
cout << endl;

v.pop_back(); // remove last element


cout << "After pop_back, size = " << [Link]() << endl;

return 0;
}

Output

Vector elements: 10 20 30
After pop_back, size = 2
2. list
A list is a doubly linked list. Insertion and deletion at any position are efficient (O(1)), but random access
is not supported directly.

Program 4: Demonstrating list

#include <iostream>
#include <list>
using namespace std;

int main() {
list<int> l = {10, 20, 30};

l.push_front(5); // insert at the beginning


l.push_back(40); // insert at the end

cout << "List elements: ";


for (int x : l) cout << x << " ";
cout << endl;

return 0;
}

Output

List elements: 5 10 20 30 40

3. deque
A deque (double-ended queue) allows fast insertion and deletion at both the front and the back, along
with random access using the [] operator.

Program 5: Demonstrating deque

#include <iostream>
#include <deque>
using namespace std;

int main() {
deque<int> dq;

dq.push_back(10);
dq.push_front(5);
dq.push_back(20);

cout << "Deque elements: ";


for (int x : dq) cout << x << " ";
cout << endl;

return 0;
}
Output

Deque elements: 5 10 20
B. Associative Containers
1. set
A set stores unique elements automatically arranged in sorted order. Duplicate insertions are ignored.

Program 6: Demonstrating set

#include <iostream>
#include <set>
using namespace std;

int main() {
set<int> s;

[Link](30);
[Link](10);
[Link](20);
[Link](10); // duplicate - ignored

cout << "Set elements (sorted, unique): ";


for (int x : s) cout << x << " ";
cout << endl;

return 0;
}

Output

Set elements (sorted, unique): 10 20 30

2. map
A map stores elements as key-value pairs, sorted by unique keys. It supports fast lookup of a value by its
key.

Program 7: Demonstrating map

#include <iostream>
#include <map>
#include <string>
using namespace std;

int main() {
map<string, int> marks;

marks["Ram"] = 85;
marks["Sita"] = 92;
marks["Hari"] = 78;

cout << "Student marks:" << endl;


for (auto &p : marks)
cout << [Link] << " -> " << [Link] << endl;
return 0;
}

Output

Student marks:
Hari -> 78
Ram -> 85
Sita -> 92

Note
map keys are automatically kept in sorted order (here, alphabetically), which is why “Hari” appears
first even though it was inserted last.
C. Container Adapters
1. stack
A stack follows Last-In-First-Out (LIFO) order. Elements are inserted and removed only from the top.

Program 8: Demonstrating stack

#include <iostream>
#include <stack>
using namespace std;

int main() {
stack<int> st;

[Link](10);
[Link](20);
[Link](30);

cout << "Stack (top to bottom): ";


while (![Link]()) {
cout << [Link]() << " ";
[Link]();
}
cout << endl;

return 0;
}

Output

Stack (top to bottom): 30 20 10

2. queue
A queue follows First-In-First-Out (FIFO) order. Elements are inserted at the back and removed from the
front.

Program 9: Demonstrating queue

#include <iostream>
#include <queue>
using namespace std;

int main() {
queue<int> q;

[Link](10);
[Link](20);
[Link](30);

cout << "Queue (front to back): ";


while (![Link]()) {
cout << [Link]() << " ";
[Link]();
}
cout << endl;

return 0;
}

Output

Queue (front to back): 10 20 30

3. priority_queue
A priority_queue always keeps the largest (by default) element at the top, regardless of insertion order.

Program 10: Demonstrating priority_queue

#include <iostream>
#include <queue>
using namespace std;

int main() {
priority_queue<int> pq;

[Link](10);
[Link](30);
[Link](20);

cout << "Priority queue (highest first): ";


while (![Link]()) {
cout << [Link]() << " ";
[Link]();
}
cout << endl;

return 0;
}

Output

Priority queue (highest first): 30 20 10


8.5.3 Iterators
An iterator is an object that behaves like a pointer and is used to point to and move across the elements
stored in an STL container. Iterators provide a uniform way to access container elements without
exposing the internal structure of the container, allowing the same algorithm to work with different
container types.

Every STL container provides begin() (pointing to the first element) and end() (pointing to one position
past the last element), which are used to define a range for traversal or for passing to algorithms.

Categories of Iterators
Iterator Type Capability Example Container

Input Iterator Read elements, move forward only (single pass) istream_iterator
Output Iterator Write elements, move forward only (single pass) ostream_iterator
Forward Iterator Read/write, move forward, multi-pass forward_list
Bidirectional Iterator Move forward and backward list, set, map
Jump to any element directly (like an array
Random Access Iterator vector, deque, array
pointer)

Program 11: Using an iterator to traverse a vector

#include <iostream>
#include <vector>
using namespace std;

int main() {
vector<int> v = {10, 20, 30, 40};

cout << "Forward traversal: ";


for (vector<int>::iterator it = [Link](); it != [Link](); ++it)
cout << *it << " "; // dereference iterator
cout << endl;

return 0;
}

Output

Forward traversal: 10 20 30 40

Program 12: Using a reverse_iterator

#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int> v = {10, 20, 30, 40};

cout << "Reverse traversal: ";


for (vector<int>::reverse_iterator it = [Link](); it != [Link](); ++it)
cout << *it << " ";
cout << endl;

return 0;
}

Output

Reverse traversal: 40 30 20 10

Program 13: Using a const_iterator (read-only traversal)

#include <iostream>
#include <list>
using namespace std;

int main() {
list<int> l = {1, 2, 3};

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


cout << *it << " ";
// *it = 100; // NOT allowed - const_iterator is read-only
}
cout << endl;

return 0;
}

Output

1 2 3

Program 14: Iterating over a map (key-value pairs)

#include <iostream>
#include <map>
#include <string>
using namespace std;

int main() {
map<string, int> age;
age["Anita"] = 20;
age["Bikash"] = 22;

for (map<string, int>::iterator it = [Link](); it != [Link](); ++it)


cout << it->first << " is " << it->second << " years old" << endl;

return 0;
}
Output

Anita is 20 years old


Bikash is 22 years old

Key Point
Use it->first / it->second for map iterators (since each element is a pair), and *it for other containers
such as vector, list, and set.
8.5.4 Algorithms
STL algorithms are generic, reusable functions defined in the <algorithm> header that perform
operations such as searching, sorting, counting, and modifying elements. They operate on a range of
elements specified by a pair of iterators [first, last) and are independent of the container type used.

Categories of Algorithms
Category Purpose Examples

Non-modifying Inspect elements without changing them find(), count(), for_each()


Modifying Change the elements or their order copy(), replace(), fill(), reverse()
Sorting Arrange elements in a specific order sort(), stable_sort()
Searching Locate elements in a sorted range binary_search()
Numeric Perform numeric computations accumulate(), iota()

Program 15: sort() — arranging elements in ascending order

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int main() {
vector<int> v = {40, 10, 30, 20};

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

cout << "Sorted: ";


for (int x : v) cout << x << " ";
cout << endl;

return 0;
}

Output

Sorted: 10 20 30 40

Program 16: find() — searching for an element

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int main() {
vector<int> v = {5, 10, 15, 20};
auto it = find([Link](), [Link](), 15);

if (it != [Link]())
cout << "Element found at position: " << (it - [Link]()) << endl;
else
cout << "Element not found" << endl;

return 0;
}

Output

Element found at position: 2

Program 17: for_each() — applying an operation to every element

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

void square(int x) {
cout << x * x << " ";
}

int main() {
vector<int> v = {1, 2, 3, 4};

cout << "Squares: ";


for_each([Link](), [Link](), square);
cout << endl;

return 0;
}

Output

Squares: 1 4 9 16

Program 18: reverse() — reversing the order of elements

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int main() {
vector<int> v = {1, 2, 3, 4, 5};

reverse([Link](), [Link]());

cout << "Reversed: ";


for (int x : v) cout << x << " ";
cout << endl;
return 0;
}

Output

Reversed: 5 4 3 2 1

Program 19: count() — counting occurrences of a value

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int main() {
vector<int> v = {1, 2, 2, 3, 2, 4};

int c = count([Link](), [Link](), 2);

cout << "Number 2 occurs " << c << " times" << endl;

return 0;
}

Output

Number 2 occurs 3 times

Program 20: accumulate() — summing elements (numeric algorithm)

#include <iostream>
#include <vector>
#include <numeric> // required for accumulate
using namespace std;

int main() {
vector<int> v = {10, 20, 30, 40};

int total = accumulate([Link](), [Link](), 0);

cout << "Sum of elements = " << total << endl;

return 0;
}

Output

Sum of elements = 100


Program 21: max_element() and min_element()

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int main() {
vector<int> v = {23, 5, 42, 17, 8};

cout << "Maximum: " << *max_element([Link](), [Link]()) << endl;


cout << "Minimum: " << *min_element([Link](), [Link]()) << endl;

return 0;
}

Output

Maximum: 42
Minimum: 5

Key Point
STL algorithms never work on containers directly — they work on a range defined by iterators (first,
last). This is what makes the same sort() or find() function usable on a vector, list, or plain C-style
array.
Summary
● STL (Standard Template Library) provides ready-made, generic, and efficient containers and
algorithms in C++.
● The four main components of STL are: Containers, Algorithms, Iterators, and Function Objects
(Functors).
● Containers store data and are grouped as Sequence (vector, list, deque), Associative (set, map),
and Container Adapters (stack, queue, priority_queue).
● Iterators are pointer-like objects used to traverse container elements; they come in input,
output, forward, bidirectional, and random-access categories.
● Algorithms (sort, find, reverse, count, accumulate, etc.) operate on iterator ranges and work
uniformly across different container types.

Review Questions
● 1. What is the Standard Template Library? List its major components.
● 2. Differentiate between sequence containers and associative containers with examples.
● 3. What is an iterator? Explain any three categories of iterators.
● 4. Write a C++ program to store five integers in a vector and print them in sorted order using STL
algorithms.
● 5. Explain the working of stack and queue container adapters with example programs.
● 6. What is a functor? How is it used to customize an STL algorithm? Give an example.
● 7. Write a program using the map container to store and display student names with their
marks.

You might also like