Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Unit - 5 Oodp Final

Download as pdf or txt
Download as pdf or txt
You are on page 1of 60

Unit - 5

•STL: Containers: Sequence and Associative Container


•Sequence container: Vector, List, Deque,Array
•Associative Containers : Map, Multimap, Iterator,
•Functions of Iterator
•Algorithms: find(), count(), sort(), search(), merge()
•Function object: for_each(), transform()
•Streams and Files: Introduction
•Classes and Errors
•Disk File Handling Reading Data and writing Data
STL: Containers: Sequence and
Associative Container
• The Standard Template Library (STL) is a collection of classes
that provide templated containers, algorithms and iterators.
• It contains common classes or algorithms so that the
programmers can use them without having to write and debug
the classes.

Components of STL

Containers Algorithms Iterators

Mrs.B.Ida Seraphim AP/CSE


Containers
Containers are objects that
• Store data
• Define the manner in which data will be stored.
• Are implemented using templates, and can, therefore, store
data of different data types.
Types of containers

Mrs.B.Ida Seraphim AP/CSE


Types of containers

Mrs.B.Ida Seraphim AP/CSE


Algorithms

• Reinforcing the concept of reusability.

• STL algorithms consists of functions that programmers can


directly use in their code to process data stored in different
containers for processing their data.

Mrs.B.Ida Seraphim AP/CSE


Algorithms in STL

Mrs.B.Ida Seraphim AP/CSE


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.

• Container :: iterator – which provides a read/write iterator.


• Container :: const_iterator – which provides a read-only
iterator.

Mrs.B.Ida Seraphim AP/CSE


Types of Iterators

Mrs.B.Ida Seraphim AP/CSE


Vector

• Vectors are sequence containers that represent dynamic arrays


that can change in size.

• Like arrays, vectors store its elements in contiguous memory


locations.

• The main advantage of vectors is that it may grow in size


when number of elements increases and shrink in size when a
number of elements are deleted.

Mrs.B.Ida Seraphim AP/CSE


Mrs.B.Ida Seraphim AP/CSE
Output
• Enter the elements of the vector : 1 2 3 4 5 6 7 8 9 10
• Elements of the vector are: 1 2 3 4 5 6 7 8 9 10
• Contents after inserting an element at 4th position - 1 2 3 4 25 5
6 7 8 9 10.
• Deleting 8th element - 1 2 3 4 25 5 6 7 9 10

Mrs.B.Ida Seraphim AP/CSE


Functions supported by vector

Mrs.B.Ida Seraphim AP/CSE


Dequeue
• A dequeue is a double-ended queue that allows insertions and
deletions at both ends.

Mrs.B.Ida Seraphim AP/CSE


List

• A list is a container in which element points to the next and


previous elements in the list.

• It supports only sequential or linear access. Therefore, if you


want to access the fourth element, you cannot access it
directly.

• You will have to start from the beginning and traverse through
the list until the desired element is found.

Mrs.B.Ida Seraphim AP/CSE


Mrs.B.Ida Seraphim AP/CSE
• Output
• Enter the elements in the 1st list: 1 2 3 4 5
• Enter the elements in the 2nd list: 9 8 7 6 5
• List 1 is: 1 2 3 4 5
• List 2 is: 9 8 7 6 5
• List 1 is: 5 4 3 2 1
• List 2 is: 5 6 7 8 9
• Merged list: 5 4 3 2 1 5 6 7 8 9

Mrs.B.Ida Seraphim AP/CSE


Functions Supported by List

Mrs.B.Ida Seraphim AP/CSE


Associative Container: Maps
• Maps are implemented as associative array in which key is
specified using the subscript operator as Scode[“Delhi”] = 011.

• To insert an entry in the map, write Scode["Chandigarh"]


=072.

• Map supports functions such as begin(), clear(), empty(),


end(), erase(), find(), insert(), size(), and swap() .

Mrs.B.Ida Seraphim AP/CSE


Mrs.B.Ida Seraphim AP/CSE
Output
Enter the city and its code
Delhi 011
Mumbai 022
Chennai 044
Kolkata 088
Number of entries in map: 6
Bangalore 080
Chandigarh 0172
Chennai 044
Delhi 011
Kolkata 088
Mumbai 022

Mrs.B.Ida Seraphim AP/CSE


Multiset

Mrs.B.Ida Seraphim AP/CSE


Mrs.B.Ida Seraphim AP/CSE
Mrs.B.Ida Seraphim AP/CSE
Mrs.B.Ida Seraphim AP/CSE
Iterators
• Iterators are objects that provide access to objects stored in a
container.
• They work as regular pointers in C++.
• They can be used to store and retrieve objects in a container
the same way a pointer accesses objects in c++.
• Types of Iterators
Iterator

Random Access
Input Forward

Output Bidirectional

Mrs.B.Ida Seraphim AP/CSE


Input Iterator
• An input iterator can be used only to retrieve a value from the
input stream it cannot be used to store a value.
• It can only move in the forward direction retrieving the objects
one by one.
• It cannot go backward and it cannot jump.

Mrs.B.Ida Seraphim AP/CSE


Output Iterator
• An output iterator can be used only to store value in an output
stream.
• It cannot be used to retrieve a value.
• It only moves in the forward direction, storing the objects one
by one.
• It cannot go backward and it cannot jump.

Mrs.B.Ida Seraphim AP/CSE


Forward Iterator
• A forward iterator can be used both to retrieve and store a
value.
• It can only move in forward direction, visiting the objects one
by one.
• It cannot go backward and it cannot jump.

Mrs.B.Ida Seraphim AP/CSE


Bidirectional Iterator
• A bidirectional iterator can be used to both retrieve and store
values.
• It moves forward and backward one item at a time.
• It cannot jump.

Mrs.B.Ida Seraphim AP/CSE


Random Access Iterator

• A Random access iterator is like bidirectional operator with


one extra capability, it can jump in both direction.

Mrs.B.Ida Seraphim AP/CSE


Hierarchical Relation
• Every forward iterator is also an input and an output iterator.
• Every bidirectional iterator is also a forward iterator.
• A random access iterartor is also a bidirectional iterator.

Mrs.B.Ida Seraphim AP/CSE


Operators Supported by Iterators

Mrs.B.Ida Seraphim AP/CSE


Algorithms – Find()

Template<class inputiterator, class T>


Inputiterator find(inputiterator first, inputiterator last, const T&
val);

Find value in the range


Returns an iterator to the first element in the range (first, last) that
compares equal to val.
If no such element is found, the function returns last.
The function uses operator== to compare the individual elements to
val.

Mrs.B.Ida Seraphim AP/CSE


Template<class inputiterator, class T>
Inputiterator find (inputiterator first, inputiterator last, const T&
val)
{
while(first !=last)
{
If(*first==val) return first;
++first;
}
return last;
}

Mrs.B.Ida Seraphim AP/CSE


#include <iostream>
#include <algorithm>
#include <vector> Output
int main() Element found in myints: 30

{
int myints[]={10,20,30,40};
int *p;
p=std::find(myints, myints+4, 30);
if (p!= myints+4)
std::cout<<“Element found in myints:”<<*p<<“\n”;
else
std::cout<<“Elements not found in myints \n”;
return 0;
}

Mrs.B.Ida Seraphim AP/CSE


Count()
Template<class inputiterator, class T>
Typename iterator_traits<inputiterator>::difference_type
count (inputiterator first, inputiterator last, const T& val);

Count apperance of value in range


Returns the number of elements in the range (first,last) that
compare equal to val.

The function uses operator== to compare the individual elements


to val.

Mrs.B.Ida Seraphim AP/CSE


Template<class inputiterator, class T>
Typename iterator_traits<inputiterator>::difference_type
Count(inputiterator first, inputiterator last, const T& val)
{
Typename iterator_traits<inputiterator>::difference_type
ret=0;
While(first!=last)
{
if(*first==val) ++ret;
++first;
}
return ret;
}

Mrs.B.Ida Seraphim AP/CSE


#include <iostream>
#include <algorithm>
#include <vector>
int main()
{
int myints[]={10,20,30,30,20,10,10,20};
int mycount=std::count (myints, myints+8, 10);
std::cout<<“10 appears”<<mycount<<“times \n”;
return 0;
}
Output
10 appears 3 times

Mrs.B.Ida Seraphim AP/CSE


Sort()
• Two Types

Default
• Template <class RandomAccessIterator>
• Void sort (RandomAccessIterator first, RandomAccessIterator
last);

Custom
• Template <class RandomAccessIterator, Class Compare>
• Void sort (RandomAccessIterator first, RandomAccessIterator
last, Compare comp);

Mrs.B.Ida Seraphim AP/CSE


Sort elements in range
• Sorts the elements in the range (first, last) into ascending
order.

• The element are compared using operator < for the first
version and comp for the second.

Mrs.B.Ida Seraphim AP/CSE


#include <iostream>
#include <algorithm>
#include <vector>
Bool myfunction (int I, int j) { return (i<j);}
Struct myclass
{
Bool operator() (int I, int j) {return (i<j);}
} myobject;
int main()
{
Int myints[]={32,71,12,45,26,80,53,33};
Std::vector<int>myvector (myints, myints+8); // 32,71,12,45,26,80,53,33
//using default comparison (operator <)
Std::sort(myvector.begin(), myvector.begin()+4); // (12,32,45,71),26,80,53,33
Mrs.B.Ida Seraphim AP/CSE
//using function as comp // 12,32,45,71,(26,33,53,80)
std::sort(myvector.begin()+4, myvector.end(), myfunction)
//using object as comp // (12,26,32,33,45,53,71,80)
std::sort(myvector.begin(), myvector.end(), myobject)
//print out content
std::cout<<“myvector contains”;
for(std::vector<int>::iterator it=myvector.begin();
it!=myvector.end(); ++it)
std::cout<<‘ ‘<<*it;
std::cout<<‘\n’;
return 0;
Output
} Myvector contains: 12 26 32 33 45 53 71 80

Mrs.B.Ida Seraphim AP/CSE


Merge()
Default
• Template<class InputIterator1, class InputIterator2, class
OutputIterator>
• OutputIterator merge (InputIterator1 first1, InputIterator1
last1, InputIterator2 first2, InputIterator2 last2, OutputIterator
result);

Custom
• Template<class InputIterator1, class InputIterator2, class
OutputIterator, class Compare>
• OutputIterator merge (InputIterator1 first1, InputIterator1
last1, InputIterator2 first2, InputIterator2 last2, OutputIterator
result, Compare comp);

Mrs.B.Ida Seraphim AP/CSE


• Merge sorted ranges
• Combines the elements in the sorted ranges (first1,last1) and
(first2,last2) into a new range beginning at result with all its
elements sorted.

Template<class InputIterator1, class InputIterator2, class


OutputIterator>
OutputIterator merge (InputIterator1 first1, InputIterator1 last1,
InputIterator2 first2, InputIterator2 last2, OutputIterator result)
{
while (true) {
if (first1==last1) return std::copy (first2, last2, result);
if (first2==last2) return std::copy (first1, last1, result);
*result++=(*first2<*first1)? *first2++: *first1++;
}
}

Mrs.B.Ida Seraphim AP/CSE


#include <iostream>
#include <algorithm>
#include <vector>
int main()
{
int first[]={5,10,15,20,25};
int second[]={50,40,30,20,10};
std::vector<int>v(10);
std::sort(first, first+5);
std::sort(second, second+5);
std::merge(first, first+5, second, second+5, v.begin());
std::cout<<“The resulting vector conatins”;
for(std::vector<int>::iterator it=v.begin(); it=v.end();++it)
std::cout<<‘ ‘<<*it;
std::cout<<‘\n’;
return 0; Output
The resulting vector contains
} 5 10 10 15 20 20 25 30 40 50

Mrs.B.Ida Seraphim AP/CSE


Search()
• Template <class ForwardIterator1, class ForwardIterator2>
• ForwardIterator1 search(ForwardIterator1 first1,
ForwardIterator1 last1, ForwardIterator2 first2,
ForwardIterator2 last2)

• Template <class ForwardIterator1, class ForwardIterator2,


class BinaryPredicate>
• ForwardIterator1 search(ForwardIterator1 first1,
ForwardIterator1 last1, ForwardIterator2 first2,
ForwardIterator2 last2, BinaryPredicate pred);

Mrs.B.Ida Seraphim AP/CSE


• Search range for subsequence
• Searches the range (first1, last1) for the first occurrence of the sequence defined by
(first2, last2) and returns an iterator to its first element or last1 if no occurrences are
found.

Template<class ForwardIterator1, class ForwardIterator2>


ForwardIterator1 search (ForwardIterator1 first1, ForwardIterator1 last1,
ForwardIterator2 first2, ForwardIterator2 last2)
{
If (first2==last2) return first1;
While (first1!=last1)
{
ForwardIterator it1= first1;
ForwardIterator it2=first2;
While (*it1==*it2){
++it1; ++it2;
If (it2==last2) return first1;
If (it1==last1) return last1;
}
++first1;
}
Return last1;
}

Mrs.B.Ida Seraphim AP/CSE


Example for Sort and Merge
#include<algorithm>
#include<functional>
int main()
{
int x[]={10,50,30,40,20};
int y[]={70,60,90,80};
sort (x,x+5,greater<int>());
sort (y,y+4);
for(int i=0;i<5;i++)
cout<<x[i]; //10,20,30,40,50
for(int j=0;j<4;j++)
cout<<y[i]; //60,70,80,90
int z[9];
merge(x,x+5,y,y+4,z);
for(int i=0;i<9;i++) //10,20,30,40,50,60,70,80,90
cout<<z[i];
return 0;
}

Mrs.B.Ida Seraphim AP/CSE


Streams and Files

Mrs.B.Ida Seraphim AP/CSE


• FSTREAM: It provides support for simultaneous input and
output operations.
• Inherits all the functions from istream and ostream classes
through iostream.

File Operations
• Opening and Closing a file
• A file can be opened in two ways
• Using the constructor of the class
• Using the member function open() of the class

Mrs.B.Ida Seraphim AP/CSE


Opening file using constructor
• File name is used to initialize the file stream object.
1. Create a file stream object to manage the stream using the appropriate
class. The class ofstream is used to create the output stream and class
ifstream to create the input stream.
2. Initialize the file object with the desired filename.
General format
• Streamclass_name file_objectname (“filename”);
• Ofstream outfile (“results”);
• ifstream infile (“results”);
Read and write operations on files
Operation Console File stream

READ Cin>>name; File_objectname>>name;

WRITE Cout<<salary; File_objectname<<salary;

Mrs.B.Ida Seraphim AP/CSE


#include<iostream.h>
#include<fstream.h>
int main() output
{
char name[10]; File object name
float sal;
ofstream outfile(“employee”);
for(int i=0;i<3;i++)
{
cout<<“Enter name and salary of employee”<<i+1; Write Mode
cin>>name>>sal;
outfile<<name<<sal;
} input
outfile.close();
ifstream inpfile(“employee”);
for(i=0;i<3;i++)
{
inpfile>>name;
Read Mode
inpfile>>sal;
cout<<“employee”<<i+1;
cout<<name<<Sal;
}
inpfile.close();
Mrs.B.Ida Seraphim AP/CSE
}
Output
Enter name and salary of employee 1: Dev 25000
Enter name and salary of employee 2: Aditya 45000
Enter name and salary of employee 3: Sarthak 60000
Employee 1: Dev 25000
Employee 2: Aditya 45000
Employee 3: Sarthak 60000

Mrs.B.Ida Seraphim AP/CSE


Opening file using member function
File position pointer
• Both istream and ostream provide member functions for
repositioning the file-position pointer.
Member Explanation
Functions
tellg() Current position of get pointer
tellp() Current position of put pointer
seekg() Moves get pointer to a specified location (input)
seekp() Moves put pointer to a specified location (output)

• Argument seek direction


Seek Directions Explanation
ios::beg Offset counted from the beginning of the stream
ios::cur Offset counted from the current stream
ios::end Offset counted from the end of the stream

Mrs.B.Ida Seraphim AP/CSE


Examples of positioning the “get” file-position pointer

• //position to the nth byte of fileobject (assumes ios::beg) – default


• fileobject.seekg(n);

• //position n bytes forward in fileobject


• fileobject.seekg(n, ios::cur);

• //position n bytes back from end of fileobject


• fileobject.seekg(n, ios::end);

• //position at end of fileobject


• fileobject.seekg(0, ios::end);

Mrs.B.Ida Seraphim AP/CSE


#include<iostream.h>
#include<fstream.h>
int main()
{ Reads in binary

streampos begin,end;
ifstream myfile(“example.bin”, ios::binary);
begin=myfile.tellg(); //current pos of the file
myfile.seekg(0, ios::end); // moves ptr to the end of file
end=myfile.tellg();
myfile.close();
cout<<“Size is:”<<(end-begin)<<“bytes”;
return 0;
Output
} Size is: 40 bytes

Mrs.B.Ida Seraphim AP/CSE


Error Handling in file I/O
• Stream State Flag

• To check errors and to ensure smooth processing C++ file


stream inherit ‘stream-state’ members from the ios class that
store the information on the status of a file that is being
currently used.
Failure in i/p & o/p operations

unused unused unused unused Hard Invalid R/W eof


error op fail

Error that cannot be recovered Beyond end of file

Mrs.B.Ida Seraphim AP/CSE


Name Meaning

eofbit 1 when end-of-file is encountered, 0 otherwise

failbit 1 when a non-fatal I/O error has occurred, 0 otherwise

Badbit 1 when a fatal I/O error has occurred, 0 otherwise

goodbit 0 value

• Error Handling Functions


Function Meaning
Int bad() Returns non-zero value if an invalid operation, 0 otherwise
Int eof() Returns non-zero(true) value if end-of-file is encountered
while reading, 0 otherwise
Int fail() Returns non-zero(true) when an input or output operation has
failed, 0 otherwise
Int good() Returns non-zero (true)if no error has occurred, 0 otherwise
Clear() Resets the error state so further operations can be attempted
Mrs.B.Ida Seraphim AP/CSE
Error handling situations in files
1. Open a non existent file in read mode.
2. Open a read only file in ios::out mode.
3. Open a file with invalid name.
4. Read beyond eof.
5. Write more data In a file stored on disk when no sufficient
disk space is available.
6. Manipulate data stored in an unopened file.
7. No file is converted with the stream object.
8. Media errors which may occur while reading/writing data.

Mrs.B.Ida Seraphim AP/CSE


#include<iostream.h>
#include<fstream.h>
#include<process.h>
#include<conio.h>
int main()
{
char fname[20];
cout<<“Enter file name”;
cin.getline(fname, 20);
ifstream fin(fname, ios::in);
{
cout<<“Error in opening the file\n”;
cout<<“press a key to exit…\n”;
return 0;
exit(1);
}
int val1,val2;
int res=0;
char op;
fin>>val1>>val2>>op;
switch(op)
{
case ‘+’: res=val+val2;
cout<<“\n”<<val1<<“+“<<val2<<“=“<<res;
break;
case ‘-’: res=val-val2;
Mrs.B.Ida Seraphim AP/CSE
cout<<“\n”<<val1<<“-“<<val2<<“=“<<res;

You might also like