Download presentation
Presentation is loading. Please wait.
Published byDonna Watkins Modified over 9 years ago
1
Object Oriented Programming in C++ Chapter 11 STL
2
Standard Template Library STL providing generic programming by these three components: Containers Iterators Algorithms
3
Containers STL Typical Containers Interfaces Constructors Element access Element insertion Destructor Iterators
4
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 ::iterator p = find(li.begin(),li.end(),42); if (p!=li.end()) { list ::iterator q = find(++p,li.end(),42); }
5
Sequence Containers Vector Deque List
6
Vector & Deque Example #include using namespace std; const int SIZE = 100; double sum(const deque &dq) { deque ::const_iterator p; double s = 0; for (p=dq.begin(); p != dq.end(); ++p) s += *p ; return s; }
7
int main() { vector vec(SIZE, 0); deque 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; }
8
Stack Example #include using namespace std; int main() { stack > 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(); }
9
Algorithms Sorting algorithms Nonmutating sequence algorithms Mutating sequence algorithms Numerical algorithms
10
Quick Sort #include 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'; }
11
Nonmutating sequence algorithms #include 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 }
12
Mutating sequence algorithms #include using namespace std; int main() { string first_names[5] = {"laura", "nira", "buzz", "debra", "twinkle"}; string last_names[5] = {"peri", "peri","berry", "berry", "star"}; vector names(first_names, first_names + 5); vector names2(10); vector ::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'; }
13
Object Oriented Programming in C++ Chapter 12 Input Output
14
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.
15
iostream Library Header Files basic stream input and output operations formatted I/O with parametrized stream manipulators file processing formatting with character arrays
16
Stream Classes ios istreamostream ofstreamiostreamifstream fstream
17
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);...
18
The put Member Function main() { char c = ‘X’ ; cout.put(c); cout.put(c).put(‘Y’); }
19
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&);...
20
The istream::get functions class istream : public virtual ios {... int get(); istream& get(char& c); istream& get(char* p, int n, char=‘\n’);... };
21
get() with no arguments returns the next input character reads white space returns EOF when end of stream is reached
22
Using get with no arguments main() { char ch; while( (ch = cin.get()) != EOF) cout.put(ch); }
23
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
24
main() { char v[80]; cin.get(v, 80, ‘\n’); char ch; if (cin.get(ch) && ch != ‘\n’) cout << “line is too long\n” ;...
25
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.
26
The putback Istream Member istream& istream::putback(char ch); places the character argument back onto the input stream #include istream& skipblanks(istream& s) { char ch; while( (ch=s.get()) == ‘ ‘) ; s.putback(ch); return s; }
27
Format State class ios { public: enum { skipws=01, //skip white space on input left=02, // padding after value right=04, // padding before value internal=010, //padding between sign/value dec=020,// decimal oct=040,// octal hex=0100,//hexadecimal showbase=0200,// show integer base showpoint=0400,// print trailing zeros uppercase=01000,// ‘E’ ‘X’, not ‘e’ ‘x’ showpos=02000,// explicit ‘+’ for integers scientific=04000,//.dddddd Edd fixed=010000,// dddd.dd unitbuf=020000,//flush after each operation. stdio=040000//flush after each char. }; //... };
28
The flags Member Function A set of formatting information using the function flags(). int options= ios::right | ios::hex | ios::fixed; cout.flags(options);
29
flags() (continued) // saving options and setting a new one int old_opt = cout.flags(new_opt); // changing one option without affecting others cout.flags(cout.flags() | ios::showpos ); // restoring old options cout.flags(old_opt);
30
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.
31
Formatting Functions class ios { //... public: int width(int w); char fill(char); int precision(int); long setf(long);... };
32
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);
33
The fill Member function Allows us to specify the fill character cout.fill(‘#’); (remains in effect until changed)
34
The precision() Member Function specifies the floating point precision the default is 6 remains set until next call to precision cout.precision(8);
35
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
36
Manipulators ios& oct(ios&); ios& dec(ios&); ios& hex(ios&); ostream& endl(ostream&); ostream& ends(ostream&); ostream& flush(ostream&); istream& ws(istream&); smanip setbase(int) smanip setfill(int); smanip setprecision(int); smanip setw(int);...
37
Example #include... int x = 12; cout << octal << x << endl;... cin >> octal >> x; … x=123; cout << “x = “ << setw(5) << setfill(‘*’)<< x << endl ;
38
User-Defined Manipulators main() { cin >> ws >> x; cout << tab << “x = “ << tab << x << endl; }
39
class ostream : public virtual ios { //... public: ostream& operator<<(ostream& (*f) (ostream&)) { return (*f)(*this); } //... }; ostream& tab(ostream& os) { return os << ‘\t’ ; }
40
Files and Streams class ostream : public virtual ios { //... public: ostream& flush(); ostream& seekp(streampos); ostream& seekp(streamoff, seek_dir); streampos tellp(); //... };
41
Seek Direction class ios { //... public: enum seek_dir { beg=0, cur=1, end=2 }; //... };
42
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”);
43
File Open Modes ios::appWrite output to end of file ios::ateMove to end of file. Allows data to be written anywhere ios::inOpen file for input ios::outOpen file for output ios::truncerase file contents ios::nocreate if file does not exist, the operation fails ios::noreplaceif the file exists, the operation fails
44
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
45
Closing a File The file is implicitly closed when the ofstream object is destroyed. We can explicitly close a file: of.close();
46
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(); //... };
47
Opening an Input File By default files are open with in mode: ifstream if(“indata”, ios::in); ifstream if(“indata);
48
Repositioning a File Reposition pointer at the beginning: if.seekg(0) reposition to the nth byte: if.seekg(n); position y bytes back from end if.seekg(y, ios::end); position at end of file: if.seekg(0, ios::end);
49
tellg and tellp tellg() and telp() return the current position: long pos = if.tellg();
50
Example - Input #include 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; }
51
Query Example #include 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; }
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.