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

Final

Here are the key steps to iterate through a vector using an iterator: 1. Declare a vector iterator variable of the appropriate type (e.g. vector<int>::iterator) 2. Initialize the iterator by assigning the return value of vec1.begin() to it 3. Use the iterator to access elements by dereferencing it (e.g. *vec1_Iter) 4. Increment the iterator to move it to the next element (e.g. vec1_Iter++) 5. Repeat steps 3-4 until the iterator reaches vec1.end() This allows iterating through the entire vector without using indexes.

Uploaded by

prathamesh sathe
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)
46 views

Final

Here are the key steps to iterate through a vector using an iterator: 1. Declare a vector iterator variable of the appropriate type (e.g. vector<int>::iterator) 2. Initialize the iterator by assigning the return value of vec1.begin() to it 3. Use the iterator to access elements by dereferencing it (e.g. *vec1_Iter) 4. Increment the iterator to move it to the next element (e.g. vec1_Iter++) 5. Repeat steps 3-4 until the iterator reaches vec1.end() This allows iterating through the entire vector without using indexes.

Uploaded by

prathamesh sathe
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/ 125

Unit 6

STANDARD TEMPLATE LIBRARY

BY
Mrs. Shubhangi Vairagar
DIT Pimpri
STANDARD TEMPLATE LIBRARY
• Introduction to STL

• Components of STL : Containers, Algorithms,


Iterator

• Containers : Sequence, Associative and Container


Adapter(Derived)

• Algorithms- basic searching and sorting algorithms,


min-max algorithm, set operations, heap sort,

• Iterators- input, output, forward, bidirectional and


random access
STANDARD TEMPLATE
LIBRARY (STL)

Developed by Alexander Stepanov and Meng Lee of HP in


1979.

Standard template library accepted in July 1994 into C++


ANSI Standard

These are called as collection of General-purpose


template classes( data structures) and functions
1
COMPONENTS OF STL

Containers

Algorithms

Iterators

2
COMPONENTS OF STL
Algorithms use iterators to interact with objects
stored in containers
Container
Algorithm1 Algorithm 2

Object1 Object2
Iterator 1 Iterator 2

Object3 Iterator 3

Algorithm 3

3
CONTAINER

Objects that hold


data (of any data Example : Array
type)

Implemented by Template
Classes

4
ALGORITHM
Example :
These are procedures
used to process the data Searching, Sorting,
contained in containers. Merging, Copying,
Initializing

Implemented by
template functions

5
ITERATOR

It is an object that Used to move


points to an through the
element in a contents of
container container

They can be
Connect Algorithms
incremented and
with Containers
decremented

6
COMPONENTS OF STL

Containers

7
CATEGORIES OF CONTAINERS

Sequence
Containers

Derived
Containers Associative
: Container Containers
Adapters

8
CONTAINERS

STL Defines 10 Containers

9
CATEGORIES OF CONTAINERS

Sequence Associative Derived

• vector • set • stack


• deque • multiset • queue
• list • map • Priority_queue
• multimap

10
Common member functions for most
STL Contaiers
Constructs an empty container.
default constructor
Containers will have other constructors as well.
Construct a copy of an already existing container
copy constructor
of the same type.
destructor Clean up when container no longer needed.
operator= Assign one container to another.
operator== Test for equality, lexicographically.
operator!= Test for inequality, lexicographically.
operator< Test for less than, lexicographically.
operator<= Test for less than or equal to, lexicographically.
operator> Test for greater than, lexicographically.
operator>= Test for greater than or equal to, lexicographically.
Commom member functions for most
STL Contaiers
empty Test if container is empty.
max_size Return maximum number of components container can hold.
size Return number of elements container currently holds.
swap Exchange all components with those of another container.
insert Insert one or more components into a container.
erase Erases one or more components from a container.
clear Erases all components from a container.
Return an iterator or const_iterator pointing to the first
begin
component.
Return an iterator or const_iterator pointing to one-past-the-last
end
component.
Return a reverse_iterator or const_reverse_iterator pointing to
rbegin
the last component.
Return a reverse_iterator or const_reverse_iterator pointing to
rend
one-before-the-first component.
Member functions found only
in sequential STL containers

assign Overwrite all components of current container.


Return a reference to a container's first
front
component.
Return a reference to a container's last
back
component.
push_back Add a value to the end of a container.
pop_back Remove the value at the end of a container.
Change the size of a container, adding or
resize
removing values.
STL Container Header Files

Sequence Associative Derived

• <vector > • set<set> • stack


• <deque> • multiset • queue
• <list> • map • Priority_queue
• multimap

10
SEQUENCE CONTAINERS
Stores elements in a linear sequence

Each element is related to other


elements by its position along the line

They allow insertion of elements

Example

Element Element Element Last


……..
0 1 2 element
11
THREE TYPES OF SEQUENCE
CONTAINERS

vector

deque list
12
Vector : Sequence Container
Expandable and dynamic array

Grows and shrinks in size

Insertion / Deletion of elements at


back

Permits direct access to any


element
13
Vector : Sequence Container

Container Header File Iterator


vector <vector> Random Access

14
vector Sequence Container
 Declarations
◦ vector <type> v;
 type: int, float, etc.
 Iterators
◦ vector<type>::const_iterator iterVar;
 const_iterator cannot modify elements
◦ vector<type>::reverse_iterator iterVar;
 Visits elements in reverse order (end to beginning)
 Use rbegin to get starting point
 Use rend to get ending point
15
vector Sequence Container
 vector functions
◦ v.push_back(value)
 Add element to end (found in all sequence containers).
◦ v.size()
 Current size of vector
◦ v.capacity()
 How much vector can hold before reallocating memory
 Reallocation doubles size
◦ vector<type> v(a, a + SIZE)
 Creates vector v with elements from array a up to (not
including) a + SIZE

16
vector Sequence Container
 vector functions
◦ v.insert(iterator, value )
 Inserts value before location of iterator
◦ v.insert(iterator, array , array + SIZE)
 Inserts array elements (up to, but not including array + SIZE) into
vector
◦ v.erase( iterator )
 Remove element from container
◦ v.erase( iter1, iter2 )
 Remove elements starting from iter1 and up to (not including)
iter2
◦ v.clear()
 Erases entire container
17
vector Sequence Container
 vector functions operations
◦ v.front(), v.back()
 Return first and last element
◦ v.[elementNumber] = value;
 Assign value to an element

18
Vector : Sequence Container
int array[5] = {12, 7, 9, 21, 13 };
vector<int> v(array,array+5);

12 7 9 21 13

v.pop_back(); v.push_back(15);

12 7 9 21 12 7 9 21 15

0 1 2 3 4

12 7 9 21 15

19
v.begin(); v[3]
Vector : Sequence Container
#include <vector>
#include <iostream>
using namespace std;
void main
{
int arr[] = {12, 7, 9, 21, 13 }; // standard C array
vector<int> v(arr, arr+5); // initialize vector with C array

while ( ) // until vector is empty


{
cout << << ” ”; // output last element of vector
// delete the last element
}
for(i=0; i<v.size(); ++i)
cout<<v[i]<<' '; 20
cout<<endl }
O/P of previous program

13 21 9 7 12
12 7 9 21 13

21
Vector : Using Iterator
#include <vector>
#include <iostream>
using namespace std;

int main()
{
vector <int> vec1;
vector <int>::iterator vec1_Iter;
vector <int>::reverse_iterator vec1_rIter;

vec1.push_back(10);
vec1.push_back(7);
vec1.push_back(3);

22
Vector : Using Iterator
cout<<"vec1 data: ";
for(int i=0; i<vec1.size(); ++i)
cout<<vec1[i]<<' ';
cout<<endl;

cout<<"\nOperation: vec1.begin()\n";
vec1_Iter = vec1.begin();

cout<<"The first element of vec1 is "<<*vec1_Iter<<endl;

cout<<"\nOperation: vec1.rbegin()\n";
vec1_rIter = vec1.rbegin();
cout<<"The first element of the reversed vec1 is “;
cout<<*vec1_rIter<<endl;
return 0; 23
}
O/P of previous program
vec1 data: 10 7 3

Operation: vec1.begin()
The first element of vec1 is10

Operation: vec1.rbegin()
The first element of the reversed vec1 is : 3

24
Vector : Using Iterator
#include <vector>
#include <iostream>
using namespace std;

int main()
{
vector <int> vec1;
vector <int>::reverse_iterator key;
vec1.push_back(7);
vec1.push_back(3);
vec1.push_back(4);
vec1.push_back(1);

25
Vector : Using Iterator
cout<<"Operation: vec1.rbegin() and vec1.rend()\n";
cout<<"vec1 data: ";

for(key = vec1.rbegin(); key != vec1.rend();


key++)
cout<<*key<<' ';
cout<<endl;
return 0;
}

26
O/P of previous program
Operation: vec1.begin() and vec1.rend()

vec1 data: 1 4 3 7

27
deque : Sequence Container
Double ended Queue

Insertion / Deletion of elements both


ends

Permits direct access to any


element

28
deque : Sequence Container

Container Header File Iterator


deque <deque> Random Access

29
Deque
#include <iostream>
#include <deque>
using namespace std;
int main ()
{
deque<int> mydeque;
mydeque.push_back (100);
mydeque.push_back (200);
mydeque.push_back (300);

cout << "\nThe final size of mydeque is "


cout<<<< mydeque.size() << “\n”;

30
Deque
cout << "Popping out the elements in mydeque:";
while (!mydeque.empty())
{
cout << mydeque.front();
mydeque.pop_front();
}

cout << "\nThe final size of mydeque is "


cout<<<< mydeque.size() << “\n”;

return 0;

}
31
O/P of previous program
The final size of mydeque is : 3

Popping out the elements in mydeque:


100 200 300

The final size of mydeque is : 0

32
list : Sequence Container

Bidirectional

Insertion / Deletion of elements


anywhwere

33
list : Sequence Container

Container Header File Iterator


list <list> Bidirectional

34
List
#include <iostream.h>
#include <list>

void print(list <char> );

main()
{
list <char> l;
list <char>::iterator p;

l.push_back('o');
l.push_back('a');
l.push_back('t');

p=l.begin(); 35
List
cout <<" "<< *p<<endl; // p refers to the 'o' in ('o', 'a', 't')
print(l);

l.insert(p, 'c'); // l is now ('c', 'o', 'a', 't') and p still refers to
'o‘
cout <<" "<< *p<<endl;

print(l);

l.erase(p);

cout <<" "<< *p<<endl; // p refers to an 'o' but it is not in l!

print(l); 36
l.erase(l.begin()); //removes front of l

print(l);

void print( list<char> a)


{
for(list<char>::iterator ai=a.begin(); ai!=a.end(); ++ai)
cout << *ai << " ";
cout << endl;
cout << "----------------"<<endl;
}

37
O/P of previous program
o
oat

o
coat

null
cat
38
at
Comparison of sequence containers

Container Random Insertion Insertion or


Access Deletion in Deletion at
middle the ends
vector Fast Slow Fast at Back
deque Fast Slow Fast at both
ends
list Slow Fast Fast at front

39
ASSOCIATIVE CONTAINERS

Non-sequential

Supports direct access to elements


using keys

The keys are typically numbers or


strings

40
FOUR TYPES OF ASSOCIATIVE
CONTAINERS
All these
store data in
a structure set
called tree
which
facilitates fast
searching
multimap Multiset

map
41
Set & Multiset : Associative
Container
Stores a number of items which contain key

Elements here are referenced by keys and not


their positions.

Example : Storing the objects of student class which are


ordered alphabetically using names as keys

Multiset allows duplicate items while set does


not

42
Set
#include <iostream>
#include <string>
#include <set>

using namespace std;

int main()
{
string a[] = {"Alice", "Bob", "Carl", "Dick", "Eve", "Fred“} ;
set<string> s(a, a+6);

set<string>::iterator p = s.begin();
while (p != s.end())
cout << *p++ << endl;
cout<<_______________________”<<endl; 43
Set
set<string>::size_type numberDeleted = s.erase(“Bob");
p = s.begin();
while (p != s.end()) cout << *p++ << endl;
cout<<_______________________”<<endl;

numberDeleted = s.erase(“William");
p = s.begin();
while (p != s.end()) cout << *p++ << endl;
cout<<_______________________”<<endl;

s.erase(s.begin());
p = s.begin();
while (p != s.end()) cout << *p++ << endl;
cout<<_______________________”<<endl;

s.erase(s.find("Carl"), s.find(“Eve"));
p = s.begin();
while (p != s.end()) cout << *p++ << endl; 44
Set
cout<<_______________________”<<endl;
s.clear();
if (s.empty())
cout << "\nThe set is now empty.";

45
O/P of previous program
Alice
Bob
Carl
Dick
Eve
Fred
____________________

Alice
Carl
Dick
Eve 46
Fred
O/P of previous program
Alice
Carl
Dick
Eve
Fred
____________________

____________________

Carl
Dick
Eve
Fred 47
O/P of previous program
Fred
____________________

The set is now empty.

48
MultiSet
#include <iostream>
#include <string>
#include <set>

class Book
{
public :
Book()
{
title = author = publisher = date = "";
}
Book(string a)
{
author = a;
title = publisher = date = ""; 49
}
MultiSet
Book(string t, string a, string p, string d)
{
title = t;
author = a;
publisher = p;
date = d;
}

string Author()
{
return author;
}

50
MultiSet
void GetInfo(string &t, string &a, string &p, string &d)
{
t = title;
a = author;
p = publisher;
d = date;
}
private:
string author;
string title;
string publisher;
string date;
};

51
Multiset
int main()
{
multiset<Book> b;
string a;

b.insert(Book("C++ book", “ABC", “McGraw-Hill", "1998"));


b.insert(Book(“Java ", “XYZ", “BB Publisher", “2001"));
b.insert(Book(“Let Us C", “Kanetkar", “McGraw-Hill ", "1997"));

multiset<Book>::iterator p = b.begin();
while (p != bookList.end())
{
cout<<*p++<<endl;
}
}; 52
O/P of previous program
C++ book
ABC
McGraw-Hill
1998

Java
XYZ
BB Publisher
2001

Let Us C
Kanetkar
McGraw-Hill
1997 46
Map & Multimap : Associative
Container
Stores pair of items, one called key and other
value

Manipulate the values using the keys associated with


them

Values are called as mapped values

Multimap allows multiple keys while map does


not

24
Map
#include <map>
#include <algorithm>
#include <iostream>
#include <string>

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

amap[”First”]=1;
amap[“Second”]=2;

cout << "Size : " << amap.size() << endl;

amap["Third"]=3;
amap[”Fourth"]=4;
cout << "Size : " << amap.size() << endl; 71
61
Map

map<string,int>::iterator it;

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


cout << "map : " << it->first << " "
<< it->second << endl;
cout << amap.find("Third")->second << endl;
return 0;
}

71
62
THREE TYPES OF DERIVED
CONTAINERS
These are
known as stack
container
adaptors

priority_queue queue

25
Stack, Queue, Priority_Queue
#include <stack>
#include <queue>
using namespace std;

int main()
{
// STL Stack
stack<int, vector<int> > S; // Changing default container

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


S.push(i);

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


{
cout << S.top() << " ";
S.top() = 2 * S.top();
cout << S.top() << endl;
S.pop();
}
// STL Queue
queue<int> Q;
for ( int i=0 ; i<10; i++ )
Q.push(i);
for ( int i=0 ; i<10; i++ )
{
cout << Q.front() << endl;
Q.pop();
}
// STL Priority Queue
priority_queue<int> P;
for ( int i=0 ; i<10; i++ )
P.push(i);
for ( int i=0 ; i<10; i++ )
{
cout << P.top() << endl;
P.pop();
}
}
Stack , Queue , Priority_Queue :
Derived Containers
Can be created from different
sequence containers

These do not support Iterators

Therefore cannot be used for data


manipulation

Support two member functions :


push( ) and pop( )
26
COMPONENTS OF STL

Containers

Algorithms

Iterators

27
2. ALGORITMS
Generic functions that handle common tasks
such as searching, sorting, comparing,
and editing

More than 60 Algortihms exist

These are not member functions or friends of


containers but are standalone template functions

To use them we include<algorithm> in the program


28
CATEGORY OF
ALGORITHMS
Retrieve or
non-
mutating(non
mdifying)

Mutating
Relational
(Modifying)

Set Sorting 29
Non-Mutating Algorithms
Operations Description

adjacent_find() Find equal adjacent elements in range

count() Count appearances of value in range

count_if Return number of elements in range


satisfying condition
equal() Test whether the elements in two ranges
are equal
find() Find value in range
30
Non-Mutating Algorithms
Operations Description

find_end Find last subsequence in range


find_first_of() Find element from set in range

find_if() Find element in range

for_each() Apply function to range

mismatch() Return first position where two ranges


differ
31
Non-Mutating Algorithms
Operations Description

search() Search range for subsequence


search_n() Search range of elements

32
Mutating Algorithms
Copy() Copy range of elements (function template )

copy_n() Copy elements (function template )

copy_if ()Copy certain elements of range (function template


)

copy_backward( )Copy range of elements


backward (function template )

move() Move range of elements (function template )

move_backward() Move range of elements 17


backward (function template ) 33
Mutating Algorithms
swapExchange values of two objects (function template )
swap_ranges Exchange values of two ranges (function template )

iter_swapExchange values of objects pointed by two iterators (function template )

transformTransform range (function template )

replaceReplace value in range (function template )

Replace_if() replace values in range (function template )

Replace_copy() Copy range


34
Mutating Algorithms

fill() Fill range with value (function template )

fill_n() Fill sequence with value (function


template )

generate ( ) Generate values for range with


function (function template )

Generate_ n( ) Generate values for sequence


with function (function template )
35
Mutating Algorithms
remove Remove value from range (function template )

remove_if()Remove elements from range (function


template )

remove_copy()Copy range removing value (function


template )

remove_copy_if()Copy range removing values (function


template )

unique Remove consecutive duplicates in range (function


template )
36
Mutating Algorithms
Unique_copy()Copy range removing
duplicates (function template )

Reverse( ) Reverse range (function template )

reverse_copyCopy range reversed (function


template )

rotate()Rotate left the elements in


range (function template )
37
Mutating Algorithms

rotate_copyCopy range rotated left (function


template )

random_shuffleRandomly rearrange elements


in range (function template )

shuffle Randomly rearrange elements in range


using generator (function template )

38
Algorithms
#include<algorithm>
#include<iostream>
using namespace std;

int main()
{
vector<int> v;
vector<int>p;
v.push_back(10); v.push_back(20); v.push_back(10);
p.push_back(60); v.push_back(40); v.push_back(50);

swap(v,p);

}
Algorithms
int n, value,arr[10],i;
int *Limit = arr + n;

cout<<“ Enter the numbers” ;


for(i =0; i< n;++i)
{
cin>>value;
arr[i] = value;
}

sort(arr, Limit);
Algorithms
cout<<“ Sorted List is” ;
for(i =0; i< n;++i)
{
cout<<arr[i];
cout<<endl;
}

return 0;
}
Algorithm…Searching Example
find , search , binary search
/ binary_search example
#include <iostream> // std::cout
#include <algorithm> // std::binary_search, std::sort
#include <vector> // std::vector

bool myfunction (int i,int j) { return (i<j); }


int main () {
int myints[] = {1,2,3,4,5,4,3,2,1};
int my2ints[] = {5,4,3,2};

vector<int> v(myints,myints+9); // 1 2 3 4 5 4 3 2 1
vector<int>::iterator it;
Algorithm…Searching Example
find , search , binary search
// using default comparison:
sort (v.begin(), v.end());

it = find(v.begin(), v.end(), 3);


cout<<“Item found at position “ <<(it-v.begin());

it = search (v.begin(), v.end(), my2ints, my2ints+4);


cout<<“Item found at position “ <<(it-v.begin());
Algorithm…Searching Example
find , search , binary search
cout << "looking for a 3... ";
if (binary_search (v.begin(), v.end(), 3))
cout << "found!\n"; else std::cout << "not found.\n";

// using myfunction as comp:


sort (v.begin(), v.end(), myfunction);

cout << "looking for a 6... ";


if (binary_search (v.begin(), v.end(), 6, myfunction))
std::cout << "found!\n"; else std::cout << "not found.\n";

Output:
return 0;
}
looking for a 3... found!
looking for a 6... not found.
Algorithm…Min Max Example
/ min max example
#include <iostream> // std::cout
#include <algorithm>

int main ()
{
cout<<“\n min(20,10) = “ <<min(20,10);
cout<<“\n min(‘a’,’b) – “ <<min(‘a’,’b’);
cout<<“\n max(‘e’, ‘f’) = <<max(‘e’,’f’);
}
Algorithm…Set Union Example
#include <iostream> // std::cout
#include <algorithm>
#include <vector> // std::vector
int main ()
{
int first[] = {5,10,15,20,25};
int second[] = {50,40,30,20,10};
vector<int> v(10); // 0 0 0 0 0 0 0 0 0 0
vector<int>::iterator it;

std::sort (first,first+5); // 5 10 15 20 25
std::sort (second,second+5); // 10 20 30 40 50
Algorithm…Set OperationsExample
it= set_union (first, first+5, second, second+5, v.begin());
// 5 10 15 20 25 30 40 50 0 0
v.resize(it-v.begin()); // 5 10 15 20 25 30 40 50

cout << "The union has " << (v.size()) << " elements:\n";
for (it=v.begin(); it!=v.end(); ++it)
cout << ' ' << *it;
cout << '\n';

return 0;
} Output:

The union has 8 elements:


5 10 15 20 25 30 40 50
Algorithm…Set Intersection
Example
#include <iostream> // std::cout
#include <algorithm>
#include <vector> // std::vector
int main ()
{
int first[] = {5,10,15,20,25};
int second[] = {50,40,30,20,10};
vector<int> v(10); // 0 0 0 0 0 0 0 0 0 0
vector<int>::iterator it;

std::sort (first,first+5); // 5 10 15 20 25
std::sort (second,second+5); // 10 20 30 40 50
Algorithm…Set Intersection
Example
it= set_intersection (first, first+5, second, second+5, v.begin());
// 5 10 15 20 25 30 40 50 0 0
v.resize(it-v.begin()); // 5 10 15 20 25 30 40 50

cout << "The intersection has has " << (v.size()) << " elements:\n";
for (it=v.begin(); it!=v.end(); ++it)
cout << ' ' << *it;
cout << '\n';

return 0;
} Output:

The intersection has 2 elements:


{10 20}
Algorithm…Set difference Example
it= set_difference (first, first+5, second, second+5, v.begin());
// 5 10 15 20 25 30 40 50 0 0
v.resize(it-v.begin()); // 5 10 15 20 25 30 40 50

cout << "The intersection has has " << (v.size()) << " elements:\n";
for (it=v.begin(); it!=v.end(); ++it)
cout << ' ' << *it;
cout << '\n';

return 0;
} Output:

The difference has 3 elements:


{5 15 25}
Iterators

input

random
forward bidirectional
access
output

39
Input & Output Iterator

Provides least functions

Used only to traverse in a


container

40
Forward Iterator

Supports all functions of input


& output iterators

Retain its position in the container

41
Bi-directional Iterator

Supports all functions of


forward iterators

Provides ability to move in


backward direction in the container

42
Random – Access Iterator

Supports all functions of bi-


directional iterators

Has the ability to jump to any


arbirtary location

43
Iterators and their characteristics
Iterator Access Direction of I/O
Method Movement Capability
Input Linear Forward Read
Output Linear Forward Write
Forward Linear Forward Read/Write
Bi- Linear Forward & Read/Write
directional Backward
Random Random Forward & Read/Write
Access Backward

44
Operations Supported by Iterators
Iterator Elemen Read Write Increme Compari
t Access nt son
Input v=*p ++ ==, !=
Output *p=v ++
Forward v=*p *p=v ++ ==, !=
Bi- v=*p *p=v ++,-- ==, !=
direction
al
Random v=*p *p=v ++,--,+,- ==,
Access !=,<,>,
& [ ] <=,>=

45
Iterator
vector<int>
array_ 17
vector<int>::iterator
4
23
12 The iterator corresponding to
the class vector<int> is of
size_ 4 the type
vector<int>::iterator

46
Iterator
The member functions begin() and end() return an
iterator to the first and past the last element of a
container
vector<int> v
v.begin()
array_ 17
4
23
12 v.end()

size_ 4
47
Iterator
One can have multiple iterators pointing to
different or identical elements in the container

vector<int> v
i1
array_ 17
4
i2
23
12
i3
size_ 4
48
Istream & ostream iterator…Input
& output iterator Example
// istream_iterator example
#include <iostream> // std::cin, std::cout
#include <iterator> // std::istream_iterator

int main () {
double value1, value2;
std::cout << "Please, insert two values: ";
std::istream_iterator<double> iit (std::cin); // stdin iterator
std::ostream_iterator<int> ot(std””cout,” ”);
value1=*iit;
++iit;
value2=*iit;
std::cout << value1 << "*" << value2 << "=" << (value1*value2) <<
'\n';
return 0; }
Inserter Example
#include <iostream> // std::cout
#include <iterator> // std::front_inserter
#include <list> // std::list
#include <algorithm> // std::copy
int main ()
{
list<int> l1, l2;
for (int i=1; i<=5; i++)
{
l1.push_back(i);
l2.push_back(i*10);
}
Inserter Example …Continued
list<int>::iterator it = l1.begin();
advance (it,3);
copy (l2.begin() , l2.end() , inserter(l1,it));

std::cout << “l1 contains:";


for ( it = l1.begin(); it!= l1.end(); ++it )
cout << ' ' << *it;
std::cout << '\n';
return 0;
}
1 2 3 10 20 30 40 50 4 5 …Output
Vector
#include<vector>
#include<iostream>

using namespace std;

void display( vector<int> &v)


{
for(int i=0;i<v.size();i++)
cout<<v[i]<<“ “;
cout<<“\n”;
}
49
Vector
int main()
{
vector<int> v; //Create vector of type int
cout<<"Initial size = " <<v.size()<<"\n";

int x;
cout<<”Enter Five values “;
for(i=0;i<5;i++)
{
cin>>x;
v.push_back(x); //Putting values into vector
} 50
Vector
cout<<“Size after adding 5 values : “ <<v.size() <<“\n”;

display(v); //Display current contents ;


v.push_back(6.6); //float value truncated to int

vector<int> :: iterator itr = v.begin(); //Iterator


itr = itr + 3;

display(v);

v,.erase(v.begin() +3 , v.begin( )+5);


display(v);
51
Vector
Constructors of Vector :

• vector <int> v; // 0 length vector

• vector<int> v(10); // 10-element int vector

•vector<int> v1(v); //Creates v1 from v

•vector<int> v(5,2); // 5-element vector of 2s or

•vector<char>v(25,’A’); //25-element vector each


// initialized with ‘A’
52
Functions of vector
Function Name Description
at ( ) Returns the value of the
element located at element in
the vector.
Example:
x = vect.at(5);
The statement above assigns
the value of the 5th element
of vect to x.
53
Functions of vector
Function Name Description
back() Returns the value of the
element located at end
element in the vector.
Example:
x = vect.back();
The statement above assigns
the value of the last element
of vect to x.
54
Functions of vector
Function Name Description
capacity( ) Returns the maximum number of
elements that may be stored in
the vector without additional
memory being allocated. (This is
not the same value as returned
by the size member function).
Example:
x = vect.capacity();
The statement above assigns the
capacity of vect to x.
55
Functions of vector
Function Name Description
clear( ) Clears a vector of all its
elements.
Example:
vect.clear();
The statement above
removes all the elements
from vect.

56
Functions of vector
Function Name Description
empty( ) Returns true if the vector is
empty. Otherwise, it returns
false.
Example:
if (vect.empty())
cout << "The
vector is empty.";
The statement above displays
the message if vect is
57
empty.
Functions of vector
Function Name Description
pop_back() Removes the last element
from the vector.
Example:
vect.pop_back();
The statement above
removes the last element of
vect, thus reducing its size
by 1.
58
Functions of vector
Function Name Description
push_back(va Stores a value in the last
lue) element of the vector. If the
vector is full or empty, a new
element is created.
Example:
vect.push_back(7);
The statement above stores
7 in the last element of
vect.
59
Functions of vector
Function Name Description
reverse() Reverses the order of the
elements in the vector (the last
element becomes the first
element, and the first element
becomes the last element.)
Example:
vect.reverse();
The statement above reverses
the order of the element in
vect.
60
Functions of vector
Function Name Description
resize(eleme Resizes a vector by elements
nts, value) elements. Each of the new
elements is initialized with the
value in value.
Example:
vect.resize(5, 1);
The statement above increases
the size of vect by 5 elements.
The 5 new elements are
initialized to the value 1.
61
Functions of vector
Function Name Description
swap(vector2 Swaps the contents of the vector
) with the contents of vector2.
Example:
vect1.swap(vect2);
The statement above swaps the
contents of vect1 and vect2.

62
Functions of vector
Function Name Description
erase(srcpos, Erases the contents of the vector
destpos) from Source position to
Destination position
Example:
vect1.erase(1,5);
The statement above erases the
contents of vect1 from position
1 to 5.

63
List
#include<list>
#include<iostream>
#include<cstdlib> //For rand( )
using namespace std;

void display( list<int> &l)


{
list<int> ::iterator p;
for(p= l.begin() ;p!= l.end(); ++p)
cout<<*p<<“ “;
cout<<“\n”;
} 65
list
int main()
{
list<int> list1; //Empty list of 0 length
list<int> list2(5); // Empty list of capacity 5

for(i=0;i<3;i++)
list1.push_back(rand( )/100 );

list<int>::iterator p;
for(p=list2.begin(); p!= list2.end();++p)
*p = rand( ) /100;
66
list
cout<< “List1 : “ <<“\n”; 0 184 63
display(list1);
cout<< “List2 : “ <<“\n”;
265 191 157 114 293
display(list2);

list1.push_front(100); 100 0 184 63 200


list1.push_back(200);
265 191 157 114 293
list2.pop_front( ) ;
191 157 114 293

display(list1);
display(list2); 67
list
list<int> listA, listB;

listA = list1;
listB = list2;
100 0 184 63 200 191 157 114 293

list1.merge(list2); 0 63 100 184 200

cout<< “List1 : “ <<“\n”;


display(list1);
listA.sort( ); 114 157 191 293
listB.sort( );
listA.merge( listB) ; 68
list
cout<< “Merged Sorted List : “ <<“\n”;
display(listA);
293 200 191 184 157 114 100 63 0
listA.reverse( );

cout<< “Reversed Merged List : “ <<“\n”;


display(listA);

return(0);

}
68
Thank you

You might also like