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

C++ Unit 6

Uploaded by

Venkata satish
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)
9 views

C++ Unit 6

Uploaded by

Venkata satish
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
You are on page 1/ 26

UNIT-6

Overview of Standard Template Library

6.1 Introduction to STL

We have studied about the template that enables us to do generic programming. Generic
functions or classes support all data types. The standard template library is an advance application
of templates. It contains several in-built functions and operators that help the programmer develop
complex programs.
The programmer only needs to include an appropriate header file to use the function or
operator from the file, such as library functions.For example, if a programmer wants to create a link
list, he/she may require to write a program that may be of 40 to 50 lines. However, using STL
functions (list algorithm), it is a task of a few minutes.
TL is vast and heterogeneous collection of reusable container classes. It consists of vectors,
lists, queues, and stacks. The STL is portable with various operating systems.he STL provides well-
coded and compiled data structures and functions that are helpful in generic programming; and it is
reusable.STL contents are defined in the namespace std. It is essential to write the statement using
namespace std at the beginning of the program.

6.2 STL Programming Model

The STL is divided into three parts. They are containers, algorithms, and iterators. All
these three parts can be used for different programming problems, and are closely associated with
one another.

Containers: A container is an object that contains data or other objects. The standard C++ library
has a number of container classes.These containers support generic programming and can be used
for handling the data of different data types. All STL container classes are declared in namespace
std; There are two types of containers, as shown in figure
• Sequence containers are created to allow sequential and random access to members.
• Associative containers allow access to their elements through a key.

Algorithms: An algorithm is a technique that is useful to handle the data stored in containers. The
STL comprises approximately 60 standard algorithms that give support to perform frequent and
primary operations such as copying, finding, sorting, merging, and initializing. The standard
algorithms are defined in the header file <algorithm>
Iterators: An iterator is an object. It behaves exactly similar to a pointer. It indicates or points to
the data element in a container. It is utilized to move between the data items of containers. Iterators
can be incremented or decremented similar to pointers. They link algorithms with containers and
handle the data stored in the containers.
6.3 Containers

There are two types of containers

1. Sequence containers
2. Associative containers
3. Derived containers

Sequence containers are developed to allow sequential and random access to all the
members. Associative containers are expanded to get their elements by values. Derived
containers such as stacks, queues, and priority queues can be created from various sequence
containers.Containers are shown in figure below

6.3.1 Sequence containers

The STL sequence containers allow controlled sequential access to elements. Sequence
containers hold data elements in a linear series, as observed in below figure.Every element is
associated by its location within the series.

The STL has three types of sequence containers:


• vectors
• lists
• deques

Iterators are used to get the elements in all these containers. All these containers have a
different speed.
a) Vectors

We know that an array is used to store similar data elements. Elements of the array are
stored in successive memory locations and are accessed in order from element number 0 onward.
The vector class exactly acts similar to an array. This class is more secure and efficient than arrays.
Vector containers may allocate some extra storage to accommodate for possible growth, and
thus the container may have an actual capacity greater than the storage strictly needed to contain its
elements
All the elements are accessed randomly; that is, they support random access to individual
elements.A vector container class provide quick access to its elements in sequence. It is used to
insert or delete an element at the end
It is defined in the header file <vector>. A vector is able to enlarge itself. For example, if a
vector declared for 5 elements is assigned 6 elements, then the vector automatically develops its
size so that it can hold the 6th element.The vectors that hold integers and floats are declared as
follows:

#include<vector>
....
vector<int> vi // for integer elements
vector <float> vf // for float elements

To declare a vector of 15 integer items, a constructor can be declared as follows:


vector<int> sale(15);

b) Lists

The list container enables the programmer to perform the usual deletion and insertion of
items. A list is also a sequence that can be accessed bi-directionally but no direct random access.. It
is defined in header file <list>. It acts as a double-linked list. Every node has a connection to both
back and front nodes in the list. The iterator is used to transverse the link.
The list class supports all the member functions of the vector class. The elements in the
linked list are accessed using pointers. The list container has a technique known as an iterator,
which is used to access the elements of the list container. An iterator is similar to a pointer. Example

#include <list>
....
list<int> l(3);

c) Deques
A deque is similar to a multiple-ended vector.A deque is similar is a double ended queue.The
deque class allows allows operations that contains insertion and deletion at one or both ends .IThe
storage of a deque is automatically expanded and contracted as needed.
deque's are not guaranteed to store all its elements in contiguous storage
locations.Elements of a deque can be scattered in different chunks of storage, with the container
keeping the necessary information internally to provide direct access to any of its elements in
constant time and with a uniform sequential interface (through iterators). Example

#include <deque>
....
deque<int> d(20);
6.3.2 Associative containers
The associative container allows attaches key to each and every element and support direct
access to elements using keys.There is no sequential ordering of elements. Data is sorted while
giving input. These containers use tree-like structures to represent elements instead of linked lists.
They facilitate fast searching, insertion, and deletion. Associative containers are divided into four
categories:
1. sets
2. multisets
3. maps
4. multimaps

All the containers listed above hold data elements in a structure called a tree. The tree
provides quick finding, deletions, and insertions. These containers perform very slowly in random
access operations and are inappropriate for sorting operations.

->Set and Multisets


• Set and multiset stores the values in sorted order.
• Elements can only be inserted or deleted but cannot be modified.
• Elements are accessed using iterators.

The essential difference between the set and the multiset is that in a set the elements must be
unique, while a multiset permits duplicate elements. Storing any duplicate elements in set is simply
ignored

Example 1:Program to implement insertion,deletion,display of set elements

#include <iostream>
#include <set>
using namespace std;
main()
{
set<int> s;
s.insert(12);
s.insert(10);
s.insert(2);
s.insert(10); //duplicate element
s.insert(12); //duplicate element

cout<<"Elements after insertion:\n";


set<int>::iterator it; //creating an iterator for set
for (it = s.begin(); it != s.end(); it++)
cout << *it << ' ';

cout<<"\nElements after deletion:\n";


s.erase(2);
for (it = s.begin(); it != s.end(); it++)
cout << *it << ' ';
}
Output:

Elements after insertion:


2 10 12
Elements after deletion:
10 12

Example 2:Program to implement insertion,deletion,display of multiset elements

#include <iostream>
#include <set>
using namespace std;
main()
{
multiset<int> s;
s.insert(12);
s.insert(10);
s.insert(2);
s.insert(10); //duplicate element
s.insert(12); //duplicate element

cout<<"Elements after insertion:\n";


set<int>::iterator it; //creating an iterator for set
for (it = s.begin(); it != s.end(); it++)
cout << *it << ' ';

cout<<"\nElements after deletion:\n";


s.erase(2);
for (it = s.begin(); it != s.end(); it++)
cout << *it << ' ';
}

Output:

Elements after insertion:


2 10 10 12 12
Elements after deletion:
10 10 12 12

*Note*:set,multisets are associative because the key and the value are the same

->Maps and Multimaps


Both stores data as pairs of key and value.While key is used for indexing and sorting,value
is used to store data.They allows manipulation of values using keys.Map and multimap are same,the
only difference is that map allows only one key for a given value,but a multimap permits use of
multiple keys for a value.Example of creating map
#include<map>
.....
.....
map <int ,char>MapType;
MapType.insert(pair <int, char>(1,'A'));
MapType.insert(pair <int, char>(2,'B'));

Example of creating multimap


#include<map>
.....
.....
multimap <char ,int>MapType1;
MapType1.insert(pair <char, int>('A',1));
MapType1.insert(pair <char, int>('B',2));

6.3.3 Derived containers


These containers are created from sequence containers. They don’t support iterators. As
there are no iterators, data cannot be manipulated. These containers support to functions -push() for
inserting and pop() for deleting elements.Examples of derived containers are: Stack, Queue, and
Priority queue.
Stack: Data is stored in Last In First Out (LIFO) order. Insertion and deletion of elements can be
done only at one end.
Queue: Data is stored in First In First Out (FIFO) order. Insertion is done at one end and deletion is
done at the other end.
PriorityQueue: The first element to be taken out is the element with highest priority.

6.4 Algorithms

Algorithms are independent template functions. They are not members or friend functions.
They enable the programmer to manipulate the data stored in various containers.
Although each type of container has its functions for performing common operations. In
addition, the STL defines more than 60 standard algorithms to facilitate users to perform extended
and complex operations.
Including the <algorithm> header file, we can use these functions.The STL algorithms
categorized under five types

1. Retrieve or non mutating


2. Mutating
3. Sorting
4. Set
5. Relational
1) Retrieve or non mutating

Non-mutating sequence algorithms enable operations that do not alter the elements in a
sequence.

Operators Use

search_n( ) Searches a sequence of a given number of same elements.


find_if( ) Searches first equivalent of a predicate in a sequence.
search( ) Searches sub-sequence in other sequence.
find_first_of( ) Searches a value from one sequence in another.
find( ) Searches first presence of a value in a sequence.
find_end( ) Searches last occurrence of a value in a sequence.
adjecent_find( ) Searches contiguous pair of objects that are identical.
mismatch( ) Searches element for which two sequences vary.
count( ) Gives the number of elements
count_if( ) Gives the number of elements that satisfies a specific criteria
equal( ) True if two series’ are the identical.
for_each( ) Performs a operation with each element.

Program to demonstrate use of operator for_each()and count()


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

void myfunction (int i) {


cout << ' ' << i;
}
main() {
vector<int> vi(4);
for ( int j=0;j<4;++j)
vi[j]=j;
cout<<" for_each() \n";
for_each(vi.begin(),vi.end(), myfunction);
cout<<"\n";

cout<<" count() \n";


cout<<count(vi.begin(),vi.end(), 3);
}

Output:
for_each()
0123
count()
1

In the above program operation myfunction is applied to each and every element of the
vector.For every myfunction is called to print the value of the vector.Algorithm count is mentioned
with three arguments vi.begin() represent beginning element of the vector,vi.end() represent
ending element of the vector, and 3 represent element that needs to count

2) Mutating

Mutating sequence algorithms enable operations that alter the elements in a sequence.

swap_ranges( ) Swaps ranges of two sequences


generate( ) Substitutes all elements with the result of an operation
copy_backward( ) Duplicate (copies) a sequence from the ends
fill( ) Fill up a series with a given value
reverse( ) Opposites (reverse) the order of elements
fill_n( ) Fill up first n elements with a given value
copy( ) Duplicates (copies) a sequence
unique( ) Erases similar contiguous elements
generate_n( ) Substitutes first n elements with the result of an operation
iter_swap( ) Exchanges elements pointed to by iterator
random_shuffle( ) Inserts elements in random order
remove( ) Erases elements of a given value
replace( ) Substitutes elements with a specified value
replace_if( ) Substitute elements matching a predicate
remove_copy_if( ) Duplicates (copies) a sequence subsequently removing elements
matching a predicate
unique_copy( ) Copies after removing similar contiguous elements
rotate( ) Rotates (turns) elements
remove if( ) Erases elements matching a predicate
remove copy( ) Duplicates (copies) a sequence subsequently removing a given value
replace copy( ) Duplicates (copies) a sequence substituting elements with a specified
value
transform( ) Applies an action to all elements
replace_copy_if( ) Duplicates (copies) a sequence substituting elements matching a
predicate
rotate_copy( ) Issues a sequence into rotate sequence
swap( ) Exchange two elements
reverse_copy( ) Copies a sequence into opposite direction

Program that fills a vector with random numbers,and demonstrate reverse and replace.

#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
void myfunction (int i) { cout << ' ' << i; }

int main()
{
vector<int> vi(8);
fill(vi.begin(),vi.begin() + 2,5);
fill(vi.begin()+2,vi.begin() + 4,6);
fill(vi.begin()+4,vi.end(),7);

cout<<" for_each() \n";

for_each(vi.begin(),vi.end(), myfunction);

cout<<"\n reverse \n";


reverse(vi.begin(),vi.end());
for_each(vi.begin(),vi.end(), myfunction);

cout<<"\n replace \n";


replace (vi.begin(), vi.end(), 7,1);
for_each(vi.begin(),vi.end(), myfunction);

Output:

for_each()
55667777
reverse
77776655
replace
11116655

The algorithm fill() is used. The fill() is a mutating algorithm, because it changes the
elements of the vector. The following statements are used to fill the element in the vector:

fill(vi.begin(),vi.begin() + 2,5);
The above statement fills the first 2 elements with the value 5. The function begin() gives a
beginning reference, and begin() + 2 gives a reference for the second.
fill(vi.begin()+2,vi.begin() + 4,6);
The above statement fills the value 6 at the third and fourth locations of the vector. Here
also, the begin() function is used.
fill(vi.begin()+4,vi.end(),7);
The above statement fills the value 7 from location number 5 to the end.

3) Sorting
List of sorting operations on containers is given as

Operators Use

binary_search( ) Performs a binary search on an indexed sequence


equal_range( ) Searches a sub-range of elements with a specified value
includes( ) Searches if a sequence is a sub-sequence of another
sequence
inplace_merge( ) Combines two successive sorted sequences
lower_bound( ) Searches the first occurrence of a given value
make_heap( ) Makes a heap from a sequence
merge( ) Combines two sorted sequences
mismatch( ) Searches the mismatch among the elements of two
sequence
nth_element( ) Places given elements in its appropriate places
partial_sort( ) Sorts a portion of a sequence
partial_sort_copy( ) Sorts a portion of a sequence and copies
pop_heap( ) Erases the uppermost elements
push_heap( ) Appends or adds an element to heap
sort( ) Sorts the sequence container
sort_heap( ) Sorts a heap
stable_partion( ) Puts elements matching an estimate first matching
relative order
stable_sort( ) Sorts arranging order of similar elements
upper_bound( ) Searches the last occurrence of a given value

Program to demonstrate sort and partial_sort

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

void myfunction (int i) { cout << ' ' << i; }

int main()
{
int n;
cout<<"\nEnter No of elements\n";
cin>>n;
vector<int> vi(n);
cout<<"\nEnter elements\n";
for ( int j=0;j<n;++j)
cin>>vi[j];

cout<<"\nPartial sort() \n";


partial_sort(vi.begin(),vi.begin() + 3, vi.end());
for_each(vi.begin(),vi.end(), myfunction);

cout<<"\nsort() \n";
sort (vi.begin(),vi.begin()+n);
for_each(vi.begin(),vi.end(), myfunction);
}
Output:

Enter No of elements
8

Enter elements
1 0 23 6 66 12 3 33

Partial sort()
0 1 3 23 66 12 6 33
sort()
0 1 3 6 12 23 33 66

In the above program,elements of vector vi is partially sorted using operation partial_sort()


up to only first 3 positions.In the next step elements of vector vi is completely sorted using
operation sort()

4) Set
List of operations on the set is given as

set_difference( ) Builds a sequence that is the variance of two ordered sets


set_intersection( ) Makes a sequence that holds the intersection of ordered
sets
set_symmetric_difference( ) Yields a set that is the symmetric variance between two
ordered sets
set_union( ) Yields sorted union of two ordered sets
includes Returns true if one set is a subset of another

Program to demonstrate union of two sets

#include <iostream>
#include <set>
#include <algorithm>
using namespace std;
void myfunction (int i)
{
cout << ' ' << i;
}
main()
{
set<int> s1;
s1.insert(12);
s1.insert(10);
set<int> s2;
s2.insert(2);
s2.insert(3);

set<int> s;
set_union(s1.begin(), s1.end(),s2.begin(), s2.end(),inserter(s, s.begin()));
cout<<"\n Union of s1,s2 is:\n";
for_each(s.begin(),s.end(), myfunction);
}

Output:

Union of s1,s2 is:


2 3 10 12

In the above program two sets s1,s2 are created with some elements.Using set_union
elements of s1 and s2 are unionized and placed in set s.

5) Relational

List of operations to test relational between sequences is given as

equal( ) Searches whether two sequences are equal


equal_range( ) Searches a sub-range of elements with a specified value
lexicographical_compare( ) Compares in ascending order one sequence with other
max( ) Returns greatest of two values
max_element( ) Returns the highest elements inside a sequence
min( ) Returns smallest of two values
min_element( ) Returns the smallest number of a sequence
mismatch( ) Searches the mismatch among the elements of two
sequence

Program to check equality of two vectors

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

main()
{
vector<int> e1;
e1.push_back(5);
e1.push_back(8);
e1.push_back(9);
vector<int> e2;
e2.push_back(5);
e2.push_back(8);
e2.push_back(9);

if (equal(e1.begin(), e1.end()+2, e2.begin()) )


cout << "The contents of both sequences are equal.\n";
else
cout << "The contents of both sequences differ.\n";
cout << "\nMax and Min of two values (a,b)\n";
cout<<"\nMin:"<<min('a', 'b') ;
cout<<"\nMax:"<<max('a', 'b') ;

vector<int>::iterator it;
it=max_element( e1.begin(),e1.end() );
cout<<"\nMaximum Element in vector:"<<*it;
it=min_element( e1.begin(),e1.end() );
cout<<"\nMinimum Element in vector:"<<*it;

Output:

The contents of both sequences are equal.

Max and Min of two values (a,b)

Min:a
Max:b
Maximum Element in vector:9
Minimum Element in vector:5

In the above program two vectors v1,v2 are created with some elements.Using equal()
method elements of v1 and v2 are compared.Minimum and maximum of two values (a,b) is
obtained using min() and max() methods.Largest and smallest elements of vector v1 is obtained
using max_element(), methods

6.4 Iterators

Iterators are pointer-like entities that are used to access the elements stored in the container.
Iterators are basically used for traversing the elements of container. This process of traversing from
one element to the next is called iterating through the container. STL offers five types of iterators
input , output, forward, bi-directional, and random access. Basic operations of these iterators is
given as

Program to demonstrate usage of iterators for list

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

int main()
{
list<char> lst;
for(char chs='A'; chs<='Z'; ++chs)
lst.push_back(chs);
list<char>::iterator pos;

for(pos = lst.begin(); pos != lst.end(); ++pos)


cout<<*pos<<' ';
}

Output:

ABCDE FGHIJKLMNOPQRSTUVWXYZ

In the above program, lst is an object of type list. The member function push_back() adds a
number in the list. In the for loop, the statement pos = lst.begin(); initializes iterator with the
beginning reference of the list (reference of the first element). The second statement pos !=
lst.end() continues the loop until the pos points to the last element of the list. The statement ++pos
dereference the iterator so that successive numbers are accessed.

6.5 Vectors

A vector is a more useful container. Similar to an array,it also stores elements in neighboring
memory locations. Each element can be directly accessed using the operator[]. A vector is able to
enlarge its size if an extra element is assigned to it. The vector class supports various functions and
they are listed in below table

Function Use

swap( ) Swap the elements in the given two vector


size( ) Provides the number of elements
resize( ) Changes the size of the vector
push_back( ) Appends an element to the end
pop_back( ) Erases the last elements
insert( ) Inserts items (elements) in the vector
erase( ) Erases given elements
end( ) Provides reference to the end of the vector
empty( ) Determine whether the vector is empty
clear( ) Erases entire elements from the vector
capacity( ) Provides the present capacity (limit) of the vector
begin( ) Provides a reference to the starting element
back( ) Provides a reference to the last element
at( ) Provides a reference to an element
Example 1: program to demonstrate usage of vector functions

#include<iostream>
#include<vector>
using namespace std;
void show(vector<int> &l) {
vector<int> :: iterator it;
for(it = l.begin(); it != l.end(); ++it)
cout<<*it<<' ';
}
main()
{
vector<int> e;
e.push_back(5);
e.push_back(8);
e.push_back(9);

cout<<"\nThe elements are : "<<"\n";


for(int i=0;i<e.size( );i++)
cout<<e[i]<<" ";

vector <int>:: iterator it;


it =e.begin();
e.insert(it,1);

it =e.end();
e.insert(it,10);
cout<<"\nAfter inserting elements at begin and end: "<<"\n";
show(e);

cout<<"\nAfter erasing 3 element "<<"\n";


it = e.begin();
e.erase(it+2);
show(e);
cout<<"\nclearing all elements"<<"\n";
e.clear();
if(e.empty())
cout<<"\nNow vector is empty"<<"\n";
}

Output:

The elements are :


589
After inserting elements at begin and end:
1 5 8 9 10
After erasing 3 element
1 5 9 10
clearing all elements
Now vector is empty

In the above program, e is an object of the vector class that can hold data of integer type.
The member function push_back() is used to add the element in the vector object. Three integer
elements 5, 8, and 9 are added to the vector. These elements are stored in contiguous memory
locations. These elements can be accessed in the same manner as we access the array elements. The
vector object name followed by the element number in the [ ] operator displays the specified
number. Here, the overloaded operator [ ] is used.
An iterator it is created to the vector and initialize to beginning and ending of the vector
using it =e.begin() and it =e.end() for insert elements using insert().The same iterator it is
incremented in for loop to display elements in vector.
Finally erase() is used to remove 3rd element in the vector.And the method e.clear() is used
to clear all elements in vector. And the method e.empty() is used to check whether list is empty (or)
not

Example 2:program to display the elements of vector object in ascending and descending
orders using iterators

#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
void show(vector<int> &l) {
vector<int> :: iterator it;
for(it = l.begin(); it != l.end(); ++it)
cout<<*it<<' ';
}
main()
{
vector<int> e;
int n,ele;
cout<<"\nEnter number of elements\n";
cin>>n;

cout<<"\nEnter elements\n";
for (int x=0;x<n;x++)
{
cin>>ele;
e.push_back(ele);
}
cout<<"\nElements in ascending order:\n";
sort (e.begin(),e.begin()+n); //sorting elements in descending order
show(e);

cout<<"\nElements in descending order:\n";


sort(e.begin(), e.end(), greater<int>()); //sorting elements in descending order
show(e);
}

Output:
Enter number of elements
4
Enter elements
2 4 0 12
Elements in ascending order:
0 2 4 12
Elements in descending order:
12 4 2 0

Example 3:Write a program to remove all odd elements from vector object

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

main()
{
vector<int> e;

int n,ele;
cout<<"\nEnter number of elements\n";
cin>>n;

cout<<"\nEnter elements\n";
for (int x=0;x<n;x++) {
cin>>ele;
e.push_back(ele);
}

vector <int> :: iterator it;

cout<<"\nVector elements after erasing all odd elements\n";

for(it = e.begin(); it != e.end(); ++it)


{
if((*it)%2!=0)
{
e.erase(it);
--it;
}
}

for(it = e.begin(); it != e.end(); ++it)


cout<<*it<<' ';
}

Output:
Enter number of elements
5
Enter elements
4 7 3 8 2
Vector elements after erasing all odd elements
482
6.5 LISTS

The list is a frequently used feature. It allows a bi-directional linear list. Element can be
inserted or deleted at both the ends. The elements in the list can be accessed sequentially. Iterators
are used for accessing individual elements of the list.

Function Task

clear( ) Erases entire elements


back( ) Provides reference to the end elements
empty( ) Determines if the list is vacant or not
begin( ) Provides reference to the first element
erase( ) Erases given element
end( ) Provides reference of the end element of the list
merge( ) Combines two sorted lists
pop_front( ) Erases the first elements
pop_back( ) Erases the last elements
remove( ) Erases elements as specified
reverse( ) Reverse the list elements
insert( ) Adds given element
push_back( ) Appends an element to the end
push_front( ) Appends an element to the front
size( ) Provides the sizes of the list
unique( ) Erases the identical elements in the list
resize( ) Changes the size of the list
swap( ) Swaps the element of a list with those in the calling list
sort( ) Sorts the list elements

Example 1: Program to demonstrate usage of vector functions

#include<iostream>
#include<list>
using namespace std;
void show( list <int> &l) {
list<int> :: iterator it;
for(it = l.begin(); it != l.end(); ++it)
cout<<*it<<' ';
}
main() {
list<int> e;
e.push_back(5);
e.push_front(8);
e.push_back(8);
e.push_front(2);
e.push_back(1);
e.push_front(11);

cout<<"\nNumbers are:\n";
show(e);
list<int> :: iterator it;
it =e.begin();
e.insert(it,1);
it =e.end();
e.insert(it,10);
cout<<"\nAfter inserting elements at begin and end: "<<"\n";
show(e);

e.pop_back();
e.pop_front();
cout<<"\nAfter poping elements at begin and end: "<<"\n";
show(e);

cout<<"\nAfter erasing 1st and element 8 inthe list"<<"\n";


it = e.begin();
e.erase(it);
e.remove(8);
show(e);

cout<<"\nclearing all elements"<<"\n";


e.clear();
if(e.empty())
cout<<"\nNow list is empty"<<"\n";
}

Output:

Numbers are:
11 2 8 5 8 1
After inserting elements at begin and end:
1 11 2 8 5 8 1 10
After poping elements at begin and end:
11 2 8 5 8 1
After erasing 1st and element 8 inthe list
251
clearing all elements
Now list is empty

Example 2:Program to display the elements of list object in ascending and descending orders
using iterators(use sort() and reverse() methods)

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

void show( list <int> &l) {


list<int> :: iterator it;
for(it = l.begin(); it != l.end(); ++it)
cout<<*it<<' ';
}
main()
{
list<int> e;
int n,ele;
cout<<"\nEnter number of elements\n";
cin>>n;

cout<<"\nEnter elements\n";
for (int x=0;x<n;x++)
{
cin>>ele;
e.push_back(ele);
}

list <int> :: iterator it;


cout<<"\nElements in ascending order:\n";
e.sort(); //sorting elements in descending order
show(e);

cout<<"\nElements in descending order:\n";


e.reverse(); //sorting elements in descending order
show(e);
}
Output:

Enter number of elements


6
Enter elements
12 3 7 3 67 4
Elements in ascending order:
3 3 4 7 12 67
Elements in descending order:
67 12 7 4 3 3

Example 3:Program to copy elements of one list object to another object. Display the contents
of both the objects.

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

void show( list <int> &l)


{
list<int> :: iterator it;
for (it=l.begin();it!=l.end(); ++it)
cout<<*it<<" ";
}

int main()
{
list <int> listX,listY;
listX.push_back(23);
listX.push_back(19);
listX.push_back(5);
listX.push_back(15);
listX.push_back(25);
listX.push_back(20);

listY=listX;

cout<<"\n Elements of listX:";


show(listX);
cout<<"\n Elements of listY:";
show(listY);
}

Output:

Elements of listX:23 19 5 15 25 20
Elements of listY:23 19 5 15 25 20

In the above program, listX and listY are two objects of the list container. The listX is
initialized with six integer elements using the push_back() functions. The statement listY = listX
copies elements of the listX object to the listY object.

Example 4:Program to merge two lists and display the merged list.

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

void show( list <int> &l)


{

list<int> :: iterator it;


for (it=l.begin();it!=l.end(); ++it)
cout<<*it<<" ";
}

int main()
{
list <int> listX,listY;
listX.push_back(23);
listX.push_back(19);
listX.push_back(5);

listY.push_back(15);
listY.push_back(25);
listY.push_back(20);

cout<<"\n Elements of listX:";


show(listX);
cout<<"\n Elements of listY:";
show(listY);

listX.merge(listY);
cout<<"\n Merged list:" ;
show(listX);
}

Output:

Elements of listX:23 19 5
Elements of listY:15 25 20
Merged list:15 23 19 5 25 20

In the above program, the objects listX and listY are initialized with three objects each with
the function push_back(). The merge() function merges the elements of two list objects into one.
The elements are merged in the calling object.
Thus, in this program, listX calls the function, and listY is sent as an argument. The listX
contains its own elements and the elements of listY. In the output, the contents of objects listX and
listY are displayed.

6.6 Maps
A map is a series of pairs of key names and values associated with it as per figure.Access of
data values depends on the key, and it is very quick. We should specify the key to get the
corresponding value.

Important functions of the map class

Function Task

clear( ) Removes all elements from the map


begin( ) Provides references of the first element
erase( ) Removes the given elements
insert( ) Inserts the elements as given
empty( ) Determines whether the map is vacant or not
end( ) Provides references to the end of the map
size( ) Provides the size of the map
find( ) Provides the location of the given elements.An iterator to the element, if
an element with specified key is found
swap( ) Swaps the elements of the given map with those of the calling map
Example 1:Program to demonstrate usage of map functions

#include<iostream>
#include<map>
#include<string>

using namespace std;

void show( map <string,int> &l)


{
map<string,int>::iterator t;
for ( t=l.begin();t!=l.end();t++)
cout<<(*t).first <<" " <<(*t).second<<"\n";cout<<"\n";
}

main()
{
string item_name;
int codeno;

map<string,int> item;
cout<<"Enter item name and code no number for 2 items: \n";

for (int i=0;i<2;i++)

{
cin>>item_name;
cin>>codeno;
item[item_name]=codeno;

}
item["PC"]=2510;
item.insert(pair<string,int> ("printer",2211));

cout<<"\nSize of map:"<<item.size();

cout<<"\nList of item name and code numbers";


show(item);

cout<<"\nAfter erasing item keyboard";


item.erase ("keyboard");
show(item);

cout<<"\nclearing all elements";


item.clear();
if(item.empty())
cout<<"\nNow Map is empty"<<"\n";

Output:
Enter item name and code no number for 2 items:
mouse 121
keyboard 345

Size of map:4
List of item name and code numbersPC 2510
keyboard 345
mouse 121
printer 2211

After erasing item keyboardPC 2510


mouse 121
printer 2211

clearing all elements


Now Map is empty

6.7 deque (Double ended queue)

deque (usually pronounced like "deck") is an irregular acronym of double-ended queue .


Double-ended queues are sequence containers with dynamic sizes that can be expanded or
contracted on both ends.
They are similar to vectors, but are more efficient in case of insertion and deletion of
elements at the end, and also the beginning. Unlike vectors, contiguous storage allocation may not
be guaranteed.The functions for deque are same as vector.

Function Use

swap( ) Swap the elements in the given two deque


size( ) Provides the number of elements
push_back( ) Appends an element to the end
pop_back( ) Erases the last elements
push_front Insert element at beginning
pop_front Delete first element
insert( ) Inserts items (elements) in the deque
erase( ) Erases given elements
end( ) Provides reference to the end of the deque
empty( ) Determine whether the deque is empty
clear( ) Erases entire elements from the deque
begin( ) Provides a reference to the starting element

Example 1:Program to demonstrate usage of Deque functions

#include<iostream>
#include<deque>
using namespace std;
void show(deque<int> &q) {
deque<int> :: iterator it;
for(it = q.begin(); it != q.end(); ++it)
cout<<*it<<' ';
}
main()
{
deque<int> q;
q.push_back(5);
q.push_front(8);
q.push_back(9);
q.push_front(2);
q.push_back(1);
q.push_front(11);
cout<<"\nThe elements are : "<<"\n";
for(int i=0;i<q.size();i++)
cout<<q[i]<<" ";
deque <int>:: iterator it;
it =q.begin();
q.insert(it,12);

it =q.end();
q.insert(it,10);
cout<<"\nAfter inserting elements at begin and end: "<<"\n";
show(q);

cout<<"\nAfter erasing 3 element "<<"\n";


it = q.begin();
q.erase(it+2);
show(q);
cout<<"\nclearing all elements"<<"\n";
q.clear();
if(q.empty())
cout<<"\nNow vector is empty"<<"\n";
}

Output:

The elements are :


11 2 8 5 9 1
After inserting elements at begin and end:
12 11 2 8 5 9 1 10
After erasing 3 element
12 11 8 5 9 1 10
clearing all elements

Now vector is empty


Unit-6 Question Bank

1. Write about the components of Standard Template Library (STL).


2. Describe the different subdivisions of STL with their definitions.
3. Explain different types of containers with examples
4. Explain different sequence containers with examples
5. Explain different Associative containers with examples
6. Explain different Derived of containers with examples
7. What is an algorithm in STL.Explain different operations in algorithm with examples?
8. Discuss about iterator in STL with example
9. Explain list in C++ STL with example
10. Discuss about map and multimap in STL?
11. Explain vector in C++ STL with example
12. Write in detail about set and multiset in STL with example
13. Explain different ways of initializing a vector with programming examples.
14. Explain Deque C++ STL with example
15. Discuss about STL programming model.
16. What is the difference between an iterator and a pointer?

Attempt the following programs

1. Write a program to demonstrate the use of operators for_each().


2. Write a C++ program to insert elements into a map.
3. Write a C++ program that fills a vector with random numbers.
4. Write a C++ program that erases all elements in a list using iterators.
5. Write a program to merge two lists and display the merged list.
6. Write a program to demonstrate the use of the fill() algorithm.
7. Write a program to copy the elements of one list object to another object. Display the
contents of both the objects.
8. Write program to count number vowels present in list
9. Write a program that deletes specified number of elements from back of deque
10. Write a program to delete duplicate elements from list
11. Write a program that display first half of the list
12. Write a program that reads the names of 10 students.Sort these names and then display it on
screen

You might also like