Object Oriented Programming in C++ Chapter 11 STL.

Post on 31-Dec-2015

227 views 4 download

transcript

Object Oriented Programming in

C++

Chapter 11

STL

Standard Template Library

STL providing generic programming by these three components:• Containers

• Iterators

• Algorithms

Containers

STL Typical Containers Interfaces• Constructors

• Element access

• Element insertion

• Destructor

• Iterators

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); }

Sequence Containers

Vector

Deque

List

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;}

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;}

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(); }}

Algorithms

Sorting algorithms

Nonmutating sequence algorithms

Mutating sequence algorithms

Numerical algorithms

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';}

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}

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';}

Object Oriented Programming in

C++

Chapter 12

Input Output

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.

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

Stream Classes

iosios

istreamistream ostreamostream

ofstreamofstreamiostreamiostreamifstreamifstream

fstreamfstream

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);...

The put Member Function

main()

{

char c = ‘X’ ;

cout.put(c);

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

}

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&);...

The istream::get functions

class istream : public virtual ios {

...

int get();

istream& get(char& c);

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

...

};

get() with no arguments

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

reached

Using get with no arguments

main()

{

char ch;

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

cout.put(ch);

}

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

main(){

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

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

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

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.

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;

}

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.

}; // ...};

The flags Member Function

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

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

cout.flags(options);

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);

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.

Formatting Functions

class ios {//...public:

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

};

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);

The fill Member function

Allows us to specify the fill character

cout.fill(‘#’);

(remains in effect until changed)

The precision() Member Function

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

cout.precision(8);

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

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);...

Example

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

User-Defined Manipulators

main()

{

cin >> ws >> x;

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

}

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

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

};

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

Files and Streams

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

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

};

Seek Direction

class ios {//...

public:enum seek_dir {

beg=0,cur=1,end=2

};//...

};

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”);

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

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

Closing a File

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

We can explicitly close a file:

of.close();

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();//...

};

Opening an Input File

By default files are open with in mode:

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

ifstream if(“indata);

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);

tellg and tellp

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

long pos = if.tellg();

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;

}

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;

}}