Advanced oops using c and c++.Pptx in Srm

yerrasaniayyapparedd 15 views 60 slides Sep 05, 2024
Slide 1
Slide 1 of 60
Slide 1
1
Slide 2
2
Slide 3
3
Slide 4
4
Slide 5
5
Slide 6
6
Slide 7
7
Slide 8
8
Slide 9
9
Slide 10
10
Slide 11
11
Slide 12
12
Slide 13
13
Slide 14
14
Slide 15
15
Slide 16
16
Slide 17
17
Slide 18
18
Slide 19
19
Slide 20
20
Slide 21
21
Slide 22
22
Slide 23
23
Slide 24
24
Slide 25
25
Slide 26
26
Slide 27
27
Slide 28
28
Slide 29
29
Slide 30
30
Slide 31
31
Slide 32
32
Slide 33
33
Slide 34
34
Slide 35
35
Slide 36
36
Slide 37
37
Slide 38
38
Slide 39
39
Slide 40
40
Slide 41
41
Slide 42
42
Slide 43
43
Slide 44
44
Slide 45
45
Slide 46
46
Slide 47
47
Slide 48
48
Slide 49
49
Slide 50
50
Slide 51
51
Slide 52
52
Slide 53
53
Slide 54
54
Slide 55
55
Slide 56
56
Slide 57
57
Slide 58
58
Slide 59
59
Slide 60
60

About This Presentation

Yes an important ppt in our college


Slide Content

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 4 th position - 1 2 3 4 25 5 6 7 8 9 10. Deleting 8 th 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 1 st list: 1 2 3 4 5 Enter the elements in the 2 nd 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 Input Output Forward Random Access 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> int main() { 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 Output Element found in myints : 30

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; } Mrs.B.Ida Seraphim AP/CSE Output 10 appears 3 times

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; } Mrs.B.Ida Seraphim AP/CSE Output Myvector contains: 12 26 32 33 45 53 71 80

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; } Mrs.B.Ida Seraphim AP/CSE Output The resulting vector contains 5 10 10 15 20 20 25 30 40 50

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. 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. 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 Mrs.B.Ida Seraphim AP/CSE 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() { char name[10]; float sal ; ofstream outfile (“employee”); for( int i =0;i<3;i++) { cout <<“Enter name and salary of employee”<<i+1; cin >>name>> sal ; outfile <<name<< sal ; } outfile.close (); ifstream inpfile (“employee”); for( i =0;i<3;i++) { inpfile >>name; inpfile >> sal ; cout <<“employee”<<i+1; cout <<name<<Sal; } inpfile.close (); } Write Mode Read Mode File object name output input

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

Opening file using member function File position pointer Both istream and ostream provide member functions for repositioning the file-position pointer. Argument seek direction Mrs.B.Ida Seraphim AP/CSE Member Functions Explanation 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) 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

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() { 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; } Mrs.B.Ida Seraphim AP/CSE Output Size is: 40 bytes Reads in binary

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. Mrs.B.Ida Seraphim AP/CSE unused unused unused unused Hard error Invalid op R/W fail eof Failure in i /p & o/p operations Error that cannot be recovered Beyond end of file

Error Handling Functions Mrs.B.Ida Seraphim AP/CSE 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 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 situations in files Open a non existent file in read mode. Open a read only file in ios ::out mode. Open a file with invalid name. Read beyond eof . Write more data In a file stored on disk when no sufficient disk space is available. Manipulate data stored in an unopened file. No file is converted with the stream object. 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; cout <<“\n”<<val1<<“-“<<val2<<“=“<<res; break; case ‘*’: res= val *val2; cout <<“\n”<<val1<<“*“<<val2<<“=“<<res; break; case ‘/’: if(val2==0) { cout <<“\n Divide by Zero Error..!!”; cout <<“\n Press any key to exit…”; return 0; exit(2); } res=val1/val2; cout <<val1<<“/”<<val2<<“=“<<res; break; } fin.close (); cout <<“\n press any key to exit…”; return 0; } Mrs.B.Ida Seraphim AP/CSE
Tags