Tải bản đầy đủ (.ppt) (29 trang)

bài giảng chú giải trình hướng đối tượng bài 5

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (269.68 KB, 29 trang )

Unit-V
Streams

The stream is an object flowing from one place to another.

In c++,a stream is used to refer to the flow of data from a particular
device to the program’s variable.

The device refer to files,keyborad,memmory arrays,console and so
on.

A stream is a series of bytes,which act either as a source from which
input data can be extracted or destination to which the output can be
sent.

Predefined Console Stream are

cin

cout

cerr

clog

Formatted I/O
C++ supports a wide variety of features to perform input or output
in different formats.They include the following,

ios stream class member functions and flags


Standard manipulators

User-defined manipulators.

ios Class Function and Flags:
The functions are

width()

precision()

fill()

setf()

unsetf()

continue

width()
Specifies the required number of fields to be used while displaying the output value.
precision()
Specifies the number of digits to be displayed after the decimal point.
fill()
Specifies a character to be used to fill the unused area of a field.By default,fill blank
space character.
unsetf()
Clears the specified flag
setf()
Sets format flag that control the form of output display.

Formatting with flags and bit fields

The member function of the ios class,setf() is
used to set flags and bit fields that control the
output.

It has the following two forms:
1.long setf(long _setbits,long _field);
2.long setf(long _setbits);
where, _setbits is one of the flags defined
in the class ios.
_fields specifies the group to
which the formattong flag belongs.

The flag and bit field table as


Flags value Bit field Effect produced
ios::left ios::adjustified Left-jusitified
ios::scientific ios::floatfield Use exponential floating
notation
ios::dec ios::basefield Decimal conversion
Manipulators

Manipultors are special functions that are specially designed to modify the working of a
stream.

Manipulators are broadly categorized into two groups namely

Proceducer is the one which generates output on an output stream


Consumer consumes input from an input stream

All the predefined manipulators are defined in the header file iomanip.h

Predefined Manipulators are of two types namely

Non-parameterized manipulators

Parameterized manipulators

Non-Parameterized manipulator are

dec sets the conversion base to 10

hex sets the conversion base to 16

oct sets the conversion base to 8

ws White space

endl Outputs anewline and flushes stream

ends Outputs a NULL character

flush Flushes the stream.
continue

Predefined parameterized manipulators are
1.setw(int width) Sets the field width

2.setprecision(int prec) Sets the floating-point precision
3.setfill(int fchar) sets the fill character
4.setbase(int base) Sets the conversion base
5.setiosflags(long flags) Sets the format flag
6.resetiosflags(long flags) reset the format flag

Custom/User defined manipulators:
Users can design their own manipulators to control the appearance of the output
depending upon their taste and need.
Syntax:
ostream & manipulator(ostream &output,arguments_if_any)
{
………
………
return output;
}
File

A file is a collection of related information defined by its creator.

There are three classes for handling files

ifstream for handling input files

ofstream for handling output files.

fstream for handling files on which both input and output ca be performed

It is necessary to include the header file fstream.h


Manipulation of a file involves the following steps

Name the file on the disk

Open the file to get the file pointer

Process the file(read/write)

Check for error while processing

Closethe file after its complete usage
File Modes

C++ provides a mechanism of openning a file in different modes in which case
the second parameter must be explicitly passed.the syntax is as follows
stream-object.open(“filename”,mode);

List of modes:
Mode value Effect on the mode
ios::in
ios::out
ios::ate
ios::app
ios::trun
ios::nocreate
ios::noreplace
ios::binary
Open for reading
Open for writing
Go to the end of file at opening time

Append mode
Truncate the ile if it already exists.
Open fails if file does not exist.
Open fails if file already exists.
Open as a binary file.
Random Access to a File
#include<iostream.h>
#include<fstream.h>
#define RED 6
Void main()
{
char reader[RED+1];
fstream fstr(“rand.txt”,ios::binary|ios::in|ios::out);
for(int i=0;i<10;i++)
fstr<<I;
fstr.seekp(2);
fstr<<“Rajalakshmi”;
fstr.seekg(4);
fstr.read(reader,RED);
reader[RED]=0;
cout<<reader<,endl;
}
Object Serialization

serialization is the process of converting a data structure or object into
a format that can be stored (for example, in a file or memory buffer, or
transmitted across a network connection link) and "resurrected" later in
the same or another computer environment.

This process of serializing an object is also called deflating or

marshalling an object. The opposite operation, extracting a data
structure from a series of bytes, is deserialization (which is also called
inflating or unmarshalling).

Serialization provides:

a method of persisting objects which is more convenient than writing their
properties to a text file on disk, and re-assembling them by reading this back
in.

a method of remote procedure calls, e.g., as in SOAP

a method for distributing objects, especially in software componentry such
as COM, CORBA, etc.

a method for detecting changes in time-varying data
Namespaces

Namespaces were introduced in ANSI C++ to provide a scope that allows different code
providers to avoid global name clashes.

The Using declaration allows the identifiers found in the standard library to be used
without being qualified.Without this declaration the pogram would have to use std::string.

The namespace std is reserved for use with the standard libraries.

The library string is part of the standar c++ library and must be included to use the
declaration string.

Syntax for namespace is

namespace namespacename
{
//code
}

Invoke the namespace by
using namespacename;
Standard template Library

STL is the C++ standard library providing generic programming for many standard data
structures and algorithms.

It provides three componets

Containers

iterators

algorithms

Containers:

It comes in two major families
(i) Sequence containers
(ii) Associative containers

Sequence containers include vectors,lists and deques

Associative containers include sets,multisets,maps and multimaps and have keys foe
looking up elements.

STL – Why?

Reuse.

Reusable core components

The programmer can focus on application development,
and rely on for portability of components such as:
strings, containers, algorithms (sort, search, etc.) and I/O
streams

STL had been designed with efficiency in mind

This lecture will be only an overview…
STL Overview

For best Generality and Reusability, most of STL’s
components are supplied as
templates
templates (functions and classes)

Three main component groups:

Containers
Containers - contain and organize other objects

Iterators
Iterators - provide a means of sequencing through the elements of a
container in some order


Algorithms
Algorithms - perform certain operations on containers’ elements.

Those components are independent of each other, pluggable, and
exchangeable, through generic interface
Containers – Overview

An STL container is an object that manages a
collection of elements

Different containers, with efficiency considerations

For search, operator== is required

For ordering, relational operators are needed, i.e. operator< is required

With common, generic interface

Also, default constructor, copy constructor, copy
assignment operator and destructor are needed

Sequence containers - Ordered collection

Associative containers – fast retrieval
Containers – Overview
Sequence Containers

vector<T>
vector<T> – dynamic array


Fast insertion at end, and allow random access

Should be your default choice, but choose wisely

Backward compatible with C : &v[0] points to the first element

deque<T>
deque<T> – double-ended queue

Offers random access, back and front insertion

Slower than vectors, no C compatibility

list<T>
list<T> – 'traditional' doubly linked list

Fast insertion anywhere, but provide only sequential access

string
string – yes, it is a STL container (a typedef actually)

etc.
Associative Containers

The sorting criterion is also a template parameter

set<T>
set<T> – add and delete elements, no duplicates

multiset<T>

multiset<T> – you can have several copies of the
same element (these are often called bags)

map<K,V>
map<K,V> – separate key and value, no duplicates

multimap<K,V>
multimap<K,V> – map allowing duplicate keys

etc.
Containers Common Functionality

Common member functions for all STL containers:

empty –
returns true if there are no elements in the container, otherwise returns false

size –
returns the number of elements currently in the container

max_size –
returns the maximum number of elements for a container

erase –
erase one or more elements from the container

clear –
erase all elements from the container

swap –

swaps the elements of two containers
List Example
#include <iostream>
#include <list>
using namespace std;
int main()
{
list<char> coll; //listcontainerforcharacterelements
//appendelementsfrom'a'to'z'
for (char c='a'; c<='z'; ++c) {
coll.push_back(c);
}
/*printallelements
*-whilethereareelements
*-printandremovethefirstelement
*/
while (! coll.empty()) {
cout << coll.front() << ' ';
coll.pop_front();
}
cout << endl;
}
Iterators

The containers provide iterator classes, enabling
element iteration and access functionality in a
common and general interface

Used as arguments to algorithms


Containers provide several iterators

Begin, End, Reverse Begin, Reverse End

5 categories – each has specific operations

Input, Output, Forward, Bidirectional, Random
Iterators

Iterators are similar to pointers

point to element in a container

iterator operators uniform for all containers

* dereferences, ++ advances pointer

container.begin() returns iterator pointing to first element

container.end() returns iterator pointing after last element
for(it = c.begin();
it != c.end();
it++)
{

}
it
Iterator Categories

All iterators: p++, ++p


Input iterators: v = *p, p1 = p2, p1 == p2, p1 != p2

Output iterators: *p = v, p1 = p2

Forward iterators: all above

Bidirectional iterators: p , p

Random access iterators: p+=i; p-=i, p+i, p-i, <,>,…
Vector Example
#include <iostream>
#include <vector>
#include <string>
using namespace std;
int main() {
vector<string> vString;
vString.push_back(“Avraham“);
vString.push_back(“Isaac“);
vString.push_back(“Yaakov“);
cout << endl << "Constant Iterator:" << endl;
vector<string>::const_iterator ci;
for(ci=vString.begin();ci!=vString.end();ci++)
cout << *ci << endl;
cout << endl << "Reverse Iterator:" << endl;
vector<string>::reverse_iterator ri;
for(ri=vString.rbegin();ri!=vString.rend();++ri)
cout << *rii << endl;

×