52
Object Oriented Programming in C++ Chapter 11 STL

Object Oriented Programming in C++ Chapter 11 STL

Embed Size (px)

Citation preview

Page 1: Object Oriented Programming in C++ Chapter 11 STL

Object Oriented Programming in

C++

Chapter 11

STL

Page 2: Object Oriented Programming in C++ Chapter 11 STL

Standard Template Library

STL providing generic programming by these three components:• Containers

• Iterators

• Algorithms

Page 3: Object Oriented Programming in C++ Chapter 11 STL

Containers

STL Typical Containers Interfaces• Constructors

• Element access

• Element insertion

• Destructor

• Iterators

Page 4: Object Oriented Programming in C++ Chapter 11 STL

Iterators Many algorithms return an identification of an element in

a container (list, vector, map, etc.). Such identifications usually have type “iterator”.

iterators know the operator ++ “sequences” (of elements in a container) are specified by

two iterators, pointing to the first and last+1 element, resp.For example:

list<int>::iterator p = find(li.begin(),li.end(),42); if (p!=li.end()) { list<int>::iterator q = find(++p,li.end(),42); }

Page 5: Object Oriented Programming in C++ Chapter 11 STL

Sequence Containers

Vector

Deque

List

Page 6: Object Oriented Programming in C++ Chapter 11 STL

Vector & Deque Example#include <iostream.h>#include <deque>#include <vector>using namespace std;const int SIZE = 100;double sum(const deque<double> &dq){ deque<double>::const_iterator p; double s = 0;

for (p=dq.begin(); p != dq.end(); ++p) s += *p ; return s;}

Page 7: Object Oriented Programming in C++ Chapter 11 STL

int main(){ vector<double> vec(SIZE, 0); deque<double> deq; int i; double sumTotal; // init and output vec for(i = 0; i < SIZE; i++){ vec[i] = i * 0.6; cout << vec[i] <<"\t"; } deq.push_front(vec.front()); // add an element to the front deq.push_back(vec.back()); // add an element to the back // Insert the remaining elements from the vector between // the first and last deque elements deq.insert(deq.begin()+1, vec.begin()+1, vec.end()-1);

sumTotal = sum(deq); cout << "The sum of the deque is : " << sumTotal << endl;}

Page 8: Object Oriented Programming in C++ Chapter 11 STL

Stack Example#include <iostream>#include <vector>#include <stack>#include <string>using namespace std;int main(){ stack<string, vector<string> > str_stack; string quote[3] = {"The wheel that squeaks the loudest\n", "Is the one that gets the grease\n", "Josh Billings\n" }; for (int i =0; i < 3; ++i) str_stack.push(quote[i]); while (!str_stack.empty()) { cout << str_stack.top(); str_stack.pop(); }}

Page 9: Object Oriented Programming in C++ Chapter 11 STL

Algorithms

Sorting algorithms

Nonmutating sequence algorithms

Mutating sequence algorithms

Numerical algorithms

Page 10: Object Oriented Programming in C++ Chapter 11 STL

Quick Sort#include <iostream>#include <algorithm>using namespace std;

const int N = 5;

int main(){ int d[N], i, *e = d + N;

for (i = 0; i < N; ++i) d[i] = rand(); sort(d, e); for (i = 0; i < N; ++i) cout << d[i] << '\t';}

Page 11: Object Oriented Programming in C++ Chapter 11 STL

Nonmutating sequence algorithms#include <iostream>#include <algorithm>#include <string>using namespace std;

int main(){ string words[5] = { "my", "hop", "mop","hope", "cope"}; string* where;

where = find(words, words + 5, "hop"); cout << *++where << endl; //mop sort(words, words + 5); where = find(words, words + 5, "hop"); cout << *++where << endl; //hope}

Page 12: Object Oriented Programming in C++ Chapter 11 STL

Mutating sequence algorithms#include <iostream>#include <algorithm>#include <string>#include <vector>using namespace std;int main(){ string first_names[5] = {"laura", "nira", "buzz", "debra", "twinkle"}; string last_names[5] = {"peri", "peri","berry", "berry", "star"}; vector<string> names(first_names, first_names + 5); vector<string> names2(10); vector<string>::iterator p; copy(last_names, last_names + 5, names2.begin()); copy(names.begin(), names.end(), names2.begin() + 5); reverse(names2.begin(), names2.end()); for (p = names2.begin(); p != names2.end(); ++p) cout << *p <<'\t';}

Page 13: Object Oriented Programming in C++ Chapter 11 STL

Object Oriented Programming in

C++

Chapter 12

Input Output

Page 14: Object Oriented Programming in C++ Chapter 11 STL

I/O Streams: cin, cout, cerr

cin is an object of class istream and is “tied” to the standard input device, normally the keyboard.

cout is an object of class ostream and is “tied” to the standard output device, normally the screen.

cerr is also an object of class ostream and is linked with the standard error device, normally the screen.

Page 15: Object Oriented Programming in C++ Chapter 11 STL

iostream Library Header Files

<iostream.h>basic stream input and output operations

<iomanip.h>formatted I/O with parametrized stream manipulators

<fstream.h>file processing

<strstream.h>formatting with character arrays

Page 16: Object Oriented Programming in C++ Chapter 11 STL

Stream Classes

iosios

istreamistream ostreamostream

ofstreamofstreamiostreamiostreamifstreamifstream

fstreamfstream

Page 17: Object Oriented Programming in C++ Chapter 11 STL

Output of Built-in Types

class ostream : public virtual ios {...

public:ostream& operator<<(const char*);ostream& operator<<(char);ostream& operator<<(short);ostream& operator<<(int);ostream& operator<<(long);ostream& operator<<(double);...

Page 18: Object Oriented Programming in C++ Chapter 11 STL

The put Member Function

main()

{

char c = ‘X’ ;

cout.put(c);

cout.put(c).put(‘Y’);

}

Page 19: Object Oriented Programming in C++ Chapter 11 STL

Input of Built-in Types

class istream : public virtual ios {// ...

public:istream& operator>>(char *);istream& operator>>(char&);istream& operator>>(short&);istream& operator>>(int&);istream& operator>>(long&);istream& operator>>(float&);...

Page 20: Object Oriented Programming in C++ Chapter 11 STL

The istream::get functions

class istream : public virtual ios {

...

int get();

istream& get(char& c);

istream& get(char* p, int n, char=‘\n’);

...

};

Page 21: Object Oriented Programming in C++ Chapter 11 STL

get() with no arguments

returns the next input character reads white space returns EOF when end of stream is

reached

Page 22: Object Oriented Programming in C++ Chapter 11 STL

Using get with no arguments

main()

{

char ch;

while( (ch = cin.get()) != EOF)

cout.put(ch);

}

Page 23: Object Oriented Programming in C++ Chapter 11 STL

The 3-argument istream::get()

reads at most n-1 characters stores input into a vector of characters stores the null character at the end stops reading when delimeter is

encountered delimeter will be the next character to

read

Page 24: Object Oriented Programming in C++ Chapter 11 STL

main(){

char v[80];cin.get(v, 80, ‘\n’);

char ch;if (cin.get(ch) && ch != ‘\n’)

cout << “line is too long\n” ;...

Page 25: Object Oriented Programming in C++ Chapter 11 STL

The ignore Istream Member

istream istream::ignore(int n=1, int delim=EOF);

skips the specified number of character the default is 1, or

until the delimiter is reached, the default is EOF.

Page 26: Object Oriented Programming in C++ Chapter 11 STL

The putback Istream Memberistream& istream::putback(char ch);

places the character argument back onto the input stream

#include <iostream.h>istream& skipblanks(istream& s){

char ch;while( (ch=s.get()) == ‘ ‘)

;s.putback(ch);return s;

}

Page 27: Object Oriented Programming in C++ Chapter 11 STL

Format Stateclass ios {public: enum {

skipws=01, //skip white space on inputleft=02, // padding after valueright=04, // padding before valueinternal=010, //padding between sign/valuedec=020, // decimaloct=040, // octalhex=0100, //hexadecimalshowbase=0200, // show integer baseshowpoint=0400, // print trailing zerosuppercase=01000, // ‘E’ ‘X’, not ‘e’ ‘x’showpos=02000, // explicit ‘+’ for integersscientific=04000, // .dddddd Eddfixed=010000, // dddd.ddunitbuf=020000, //flush after each operation.stdio=040000 //flush after each char.

}; // ...};

Page 28: Object Oriented Programming in C++ Chapter 11 STL

The flags Member Function

A set of formatting information using the function flags().

int options= ios::right | ios::hex | ios::fixed;

cout.flags(options);

Page 29: Object Oriented Programming in C++ Chapter 11 STL

flags() (continued)

// saving options and setting a new oneint old_opt = cout.flags(new_opt);

// changing one option without affecting otherscout.flags(cout.flags() | ios::showpos );

// restoring old optionscout.flags(old_opt);

Page 30: Object Oriented Programming in C++ Chapter 11 STL

The setf(long) and unsetf(long) Member Functions

setf(long) sets the options specified by its argument, without changing any of the other options.

unsetf(long) unsets the options specified by its argument.

Page 31: Object Oriented Programming in C++ Chapter 11 STL

Formatting Functions

class ios {//...public:

int width(int w);char fill(char);int precision(int);long setf(long);...

};

Page 32: Object Oriented Programming in C++ Chapter 11 STL

The width Member Function

Allows us to specifie the minimum number of characters to be used for the next numeric or string output operations.

cout.width(5);

Page 33: Object Oriented Programming in C++ Chapter 11 STL

The fill Member function

Allows us to specify the fill character

cout.fill(‘#’);

(remains in effect until changed)

Page 34: Object Oriented Programming in C++ Chapter 11 STL

The precision() Member Function

specifies the floating point precision the default is 6 remains set until next call to precision

cout.precision(8);

Page 35: Object Oriented Programming in C++ Chapter 11 STL

Example

cout.width(5);cout.fill(‘*’);cout.setf(ios::left, ios::adjustfield);cout << “x = “ << x ;

cout.setf(ios::scientific, ios::floatfield);cout << 1234.56789;output: 1.234568e+03

cout.setprecision(7);cout << 1234.56789 << ‘\n’;output: 1234.569

Page 36: Object Oriented Programming in C++ Chapter 11 STL

Manipulatorsios& oct(ios&);ios& dec(ios&);ios& hex(ios&);ostream& endl(ostream&);ostream& ends(ostream&);ostream& flush(ostream&);istream& ws(istream&);

smanip<int> setbase(int)smanip<int> setfill(int);smanip<int> setprecision(int);smanip<int> setw(int);...

Page 37: Object Oriented Programming in C++ Chapter 11 STL

Example

#include <iomanip.h>...int x = 12;cout << octal << x << endl;...cin >> octal >> x;…x=123;cout << “x = “ << setw(5) << setfill(‘*’)<< x << endl ;

Page 38: Object Oriented Programming in C++ Chapter 11 STL

User-Defined Manipulators

main()

{

cin >> ws >> x;

cout << tab << “x = “ << tab << x << endl;

}

Page 39: Object Oriented Programming in C++ Chapter 11 STL

class ostream : public virtual ios { //... public:ostream& operator<<(ostream& (*f) (ostream&))

{ return (*f)(*this); }// ...

};

ostream& tab(ostream& os){ return os << ‘\t’ ; }

Page 40: Object Oriented Programming in C++ Chapter 11 STL

Files and Streams

class ostream : public virtual ios { //...public:

ostream& flush();ostream& seekp(streampos);ostream& seekp(streamoff, seek_dir);streampos tellp();// ...

};

Page 41: Object Oriented Programming in C++ Chapter 11 STL

Seek Direction

class ios {//...

public:enum seek_dir {

beg=0,cur=1,end=2

};//...

};

Page 42: Object Oriented Programming in C++ Chapter 11 STL

Opening an Output File

ofstream of(“data”, ios::out);

in ios::out mode the file is truncated by default, ofstream implies that the file

is opened with the out mode.

ofstream of(“data”);

Page 43: Object Oriented Programming in C++ Chapter 11 STL

File Open Modes ios::app Write output to end of file ios::ate Move to end of file. Allows data to be

written anywhere

ios::in Open file for input ios::out Open file for output ios::trunc erase file contents ios::nocreate if file does not exist, the operation

fails

ios::noreplace if the file exists, the operation fails

Page 44: Object Oriented Programming in C++ Chapter 11 STL

Testing the Success of open

if ( ! of ) ...

Possible errors:• opening a non-existent file

• attempting to read without permission

• attempting to write with no disk space

Page 45: Object Oriented Programming in C++ Chapter 11 STL

Closing a File

The file is implicitly closed when the ofstream object is destroyed.

We can explicitly close a file:

of.close();

Page 46: Object Oriented Programming in C++ Chapter 11 STL

Members of istream

class istream : public virtual ios {//...

public:int peek();istream& putback(char c);istream& seekg(streampos);istream& seekg(streamoff, seek_dir);streampos tellg();//...

};

Page 47: Object Oriented Programming in C++ Chapter 11 STL

Opening an Input File

By default files are open with in mode:

ifstream if(“indata”, ios::in);

ifstream if(“indata);

Page 48: Object Oriented Programming in C++ Chapter 11 STL

Repositioning a File Reposition pointer at the beginning:

if.seekg(0)

reposition to the nth byte:if.seekg(n);

position y bytes back from endif.seekg(y, ios::end);

position at end of file:if.seekg(0, ios::end);

Page 49: Object Oriented Programming in C++ Chapter 11 STL

tellg and tellp

tellg() and telp() return the current position:

long pos = if.tellg();

Page 50: Object Oriented Programming in C++ Chapter 11 STL

Example - Input#include <iostream.h>#include <fstream.h>#include <iomanip.h>#include <stdlib.h>main(){ char name[10]; int quantity; ifstream inf("inventory", ios::in); if( !inf ) {

cerr << "Cannot open file\n";exit(1);

} while( inf >> name >> quantity)

cout << setiosflags(ios::left) << setw(10) << name << setiosflags(ios::right) << setw(7) << quantity << endl;

}

Page 51: Object Oriented Programming in C++ Chapter 11 STL

Query Example#include <iostream.h>#include <fstream.h>#include <iomanip.h>#include <stdlib.h>main(){ char name[10]; int quantity; char item[10]; ifstream inf("inventory", ios::in); if( !inf ) {

cerr << "Cannot open file\n";exit(1);

} cout << "item name"; cin >> item;

inf >> name >> quantity; while( !inf.eof() ) {

if( !strcmp(name, item) ) cout << setiosflags(ios::left) << setw(10) << name

<< setiosflags(ios::right)<< setw(7) << quantity <<

endl;inf >> name >> quantity;

}}

Page 52: Object Oriented Programming in C++ Chapter 11 STL