OOP

192
Course introduction Lesson 1 - Course Goals Lesson 2 - Course introduction Lesson 3 - Prerequisites Lesson 4 - What you need Lesson 5 - Course resources Lesson 6 - Tutors Lesson 7- Course project Storage classes Lesson 1 - Module goals Lesson 2 - Storage class qualifiers Sidebar: Storage class qualifiers (FlipBook transcript) Lesson 3 - Functions and storage classes Sidebar: Storage class qualifiers (FlipBook transcript) Lesson 4 - Language linking Sidebar: Difference between the processes of language linking (FlipBook transcript) Lesson 5 - Dynamic allocation and storage class Lesson 6 - Namespaces Sidebar: Different terms related to namespaces (FlipBook transcript) Lesson 7- Namespaces and their use Sidebar:Defining and using namespace in a C++ program (FlipBook transcript) Lesson 8- Nested namespaces Sidebar: Declaring and using nested namespaces (FlipBook transcript) Lesson 9- Unnamed namespaces Sidebar: Usage of unnamed namespaces (FlipBook transcript) Lesson 10- Module wrap-up Store data in singly linked lists Lesson 1 - Module goals Lesson 2 - Linked lists Sidebar: Advantages and disadvantages of linked lists over arrays (FlipBook transcript) Lesson 3 - Different types of linked lists Sidebar: Most widely used linked lists (FlipBook transcript) Lesson 4 - Singly linked lists Sidebar: Implementing singly linked list (FlipBook transcript) Lesson 5 -Node addition Sidebar: How nodes are added in an empty singly linked list (FlipBook transcript) Sidebar: How nodes are added when a linked list is not empty (FlipBook transcript) Lesson 6 - List traversing Sidebar: Traversing a linked list (FlipBook transcript) Lesson 7- Node deletion

description

OOP

Transcript of OOP

Course introduction Lesson 1 - Course Goals Lesson 2 - Course introduction Lesson 3 - Prerequisites Lesson 4 - What you need Lesson 5 - Course resources Lesson 6 - Tutors Lesson 7- Course project Storage classes Lesson 1 - Module goals Lesson 2 - Storage class qualifiers Sidebar: Storage class qualifiers (FlipBook transcript) Lesson 3 - Functions and storage classes Sidebar: Storage class qualifiers (FlipBook transcript) Lesson 4 - Language linking Sidebar: Difference between the processes of language linking (FlipBook transcript) Lesson 5 - Dynamic allocation and storage class Lesson 6 - Namespaces Sidebar: Different terms related to namespaces (FlipBook transcript) Lesson 7- Namespaces and their use Sidebar:Defining and using namespace in a C++ program (FlipBook transcript) Lesson 8- Nested namespaces Sidebar: Declaring and using nested namespaces (FlipBook transcript) Lesson 9- Unnamed namespaces Sidebar: Usage of unnamed namespaces (FlipBook transcript) Lesson 10- Module wrap-up Store data in singly linked lists Lesson 1 - Module goals Lesson 2 - Linked lists Sidebar: Advantages and disadvantages of linked lists over arrays (FlipBook

transcript) Lesson 3 - Different types of linked lists

Sidebar: Most widely used linked lists (FlipBook transcript) Lesson 4 - Singly linked lists Sidebar: Implementing singly linked list (FlipBook transcript) Lesson 5 -Node addition Sidebar: How nodes are added in an empty singly linked list (FlipBook transcript) Sidebar: How nodes are added when a linked list is not empty (FlipBook transcript) Lesson 6 - List traversing Sidebar: Traversing a linked list (FlipBook transcript) Lesson 7- Node deletion

Sidebar: Deleting a node from a singly linked list (FlipBook transcript) Sidebar: Code for implementing a singly linked list (FlipBook transcript) Lesson 8- Module wrap-up Store data in doubly linked lists Lesson 1- Module goals Lesson 2- Doubly linked list Sidebar: Doubly linked lists (FlipBook transcript) Lesson 3- Node addition Sidebar: Empty doubly linked list (FlipBook transcript) Sidebar: Linked list is not empty (FlipBook transcript) Lesson 4- List traversing Sidebar: Traversing doubly linked list (FlipBook transcript) Lesson 5- Node deletion Sidebar: Deleting a node from a doubly linked list (FlipBook transcript) Lesson 6- Doubly linked list implementation Sidebar: Implementing a doubly linked list (FlipBook transcript) Lesson 7- Module wrap-up Debugging and exception handling Lesson 1- Module goals Lesson 2- Code debugging Sidebar: Debugging code in a C++ program (Simulation transcript) Sidebar: Utility of the Step Over and Step Into buttons (FlipBook transcript) Lesson 3- Exception handling Lesson 4- The mechanism of exception handling Sidebar: Structure and keywords related to exception handling (FlipBook transcript) Lesson 5- Exception handling demonstration Sidebar: Exception handling mechanism in a C++ program (FlipBook transcript) Lesson 6- Nested exception handling Sidebar: Implementing nested exception handling (FlipBook transcript) Lesson 7- Multiple try and catch blocks Sidebar: Multiple try and catch blocks within a program (MouseOver transcript) Lesson 8- Unhandled exceptions Lesson 9- Module wrap-up Data transmission through streams Lesson 1 -Module goals Lesson 2 - File I/O Lesson 3 - Stream class hierarchy Lesson 4 - Stream buffering Lesson 5 - String I/O Sidebar: Reading and writing operations on a file (FlipBook transcript) Lesson 6 - Character I/O

Sidebar: Insert and fetch data to and from a file (FlipBook transcript) Lesson 7- Object I/O Sidebar: Object is used for reading and writing (MouseOver transcript) Lesson 8- Input/Output with multiple objects Sidebar: File I/O using multiple objects (FlipBook transcript) Lesson 9- Module wrap-up Work with templates Lesson 1 - Module goals Lesson 2 - Template Lesson 3 - Function template Sidebar: Create a function template and refer it from your program (FlipBook

transcript) Lesson 4 -Template class

Sidebar: Create a class template and refer it from your program (FlipBook transcript) Lesson 5 - Template with a family of classes Sidebar: Template with a family of classes (FlipBook transcript) Lesson 6- Template versatility Lesson 7- Template specialization Sidebar: The processes involved in template specialization (FlipBook transcript) Lesson 8- Module wrap-up Getting acquainted with Standard Template Library Lesson 1 - Module goals Lesson 2 - Standard Template Library Lesson 3 - Basic elements of STL Sidebar: Brief description of the elements of STL (MouseOver transcript) Lesson 4 -Containers Sidebar: Different types of containers (FlipBook transcript)

Sidebar: Details of some containers (FlipBook transcript) Lesson 5 - Algorithms Sidebar: Algorithms (FlipBook transcript) Lesson 6 - Iterators Sidebar: Iterators (FlipBook transcript) Lesson 7- Function objects Sidebar: Different types of function objects (MouseOver transcript) Lesson 8- Additional components of STL Sidebar: Different types of adaptors in STL (FlipBook transcript) Lesson 9- Module wrap-up Run-time type information and type casting Lesson 1 - Module goals Lesson 2 - The role of RTTI

Lesson 3 - Dynamic cast operators Sidebar: Dynamic_cast operator (FlipBook transcript) Lesson 4 - Typeid operators and type_info structures Sidebar: Typeid operators and type_info structures (MouseOver transcript) Lesson 5 - Implementation of RTT Lesson 6- Type casting Sidebar: Different types of type cast operatorsr (FlipBook transcript) Lesson 7- Module wrap-up Course Project Lesson 1 - Module goals Lesson 2 - Scenario Lesson 3 - Implement doubly linked list Lesson 4 - File I/O through streams Lesson 5 - Create a class template and use the same with family of classes

Course conclusion Lesson 1 - Course Goals Lesson 2 - Course conclusion Lesson 3 - We'd love your feedback

Course introduction

Copyright© 2002 DigitalThink, Inc. All Rights Reserved.

Course introduction

Course introduction

Welcome to Advanced Programming in C++. This course guides you through the advancedconcepts of C++ programming and object-oriented methodologies. You will learn how C++handles exceptions, implements templates and types.

Along with the other two courses in this series, this course gives you an overview of the advancedfeatures of C++ programming.

Course goals

After completing the course, you will be able to:

Exception handling●

Templates and Collections●

Input and output in C++ programs●

Run time type identification●

The SeriesAdvanced Programming in C++ is the third of three courses in the Introduction toProgramming in C++ Series. For more information on other courses including that can help yougain Microsoft certification, please visit the Catalog page.

How you'll learnIn this course, you'll learn skills required to successfully create derived classes and polymorphicfunctions. These skills will be taught using several types of interactive applets, includingMouseOvers, FlipBooks, and Simulations. You will test your knowledge periodically withexercises, quizzes, and ordering and matching activities. For additional information on these andother applets, see the Course Orientation.

Problem Solver exercisesWe have created exercises throughout the series in which you apply your knowledge about ObjectOriented Programming in C++ to various scenarios. You will submit your solutions to theProblem Solver exercises to tutors, although you should also consider using the discussion groupsas a forum for sharing responses.

First-time students: To get the most out of this course, take the Course Orientation.

Copyright© 2002 DigitalThink, Inc. All Rights Reserved.

Course introduction

Prerequisites

In order to get the most out of this course, you should have:

DigitalThink's Object-Oriented Programming in C++ or equivalent knowledge andexperience

Copyright© 2002 DigitalThink, Inc. All Rights Reserved.

Course introduction

What you need

Platform supportYou can take this course on Windows, Macintosh, or Unix platforms.

Required softwareAn ANSI C++ Compiler or a Bloodshed compiler

Monitor resolutionThe Simulations in this course require a minimum monitor desktop area of 800x600. If yourresolution is set lower than this, some of the Simulation windows may be too large to fit entirelyon your screen.

Copyright© 2002 DigitalThink, Inc. All Rights Reserved.

Course introduction

Course resources

There are numerous resources offered with this course that will help you to complete itsuccessfully. The greatest resource is the Course Orientation, which you should take right now ifyou haven't already. There, you'll learn what to expect with regard to course structure,interactivity, and assessment.

In addition to the Orientation, there are several other resources available to you. You'll comeacross those listed below as you progress through the course.

Resources and Help pagesYou can find Web links on the Resources page. Remember, you can reach the Resources page atany time throughout the course by clicking the Resources button on the toolbar. And if you havequestions, assistance is always available on the Help page.

GlossaryThroughout this course, you'll have the opportunity to review definitions of key terms. Theseterms are defined in the course glossary. The terms appear as maroon, italicized, and underlinedin the lesson text. Clicking a glossary term opens a pop-up window with the definition. You cantry it now. The terms appearing in interactivities that are italicized, underlined and blue do notfunction as hyperlinks. To view to the definitions of these terms, check the Glossary.

TipWe encourage you to use the course Syllabus frequently. From the Syllabus, you may go to anylesson in this course. You may also find out how far you have progressed in the course and howmuch more you have to go before finishing a module or the course itself. To access the Syllabus,just click the Syllabus button on the toolbar.

Course PDFYou can download a compressed file from the Resources page that contains a PDF file of theentire course. This PDF file provides the lesson, quiz, and exercise content so you can read andreview the course material offline at your convenience. The PDF file is not required to completethis course.

This course also has a separate PDF file containing the solutions for all the course exercises. TheExercise Solutions PDF is also available for download as a compressed file on the Resourcespage.

You will need Adobe Acrobat Reader 3.0 or greater to view a PDF file. If you don't have AcrobatReader, you can download it from the Adobe Web site

Copyright© 2002 DigitalThink, Inc. All Rights Reserved.

Course introduction

Tutors

To share your ideas and get feedback on the work you do in this course is through your tutors.The course tutors are experts in the subject of this course. They may review your exercisesubmissions and respond to them by email if the exercises so require. You can also email thetutors whenever you have a question or get stuck in a lesson or exercise.

How to send email to the tutors

Let's walk through the process of sending e-mail to your course tutors:

1. Click the Tutor tab on the resources pane.

2. The Resources pane expands.

3. Type a subject for your query in the Subject box.

4. Type your query in the message box.

5. Click the Submit button to the right of the box. The resource pane collapses and the message issent.

Copyright© 2002 DigitalThink, Inc. All Rights Reserved.

Course introduction

Course project

To better prepare you to program using C++, and to provide a final opportunity to practice someof what you have learned, we have designed a case study course project. You'll find it in the finalmodule in this course.

In the course project, you will assume the role of a C++ solution developer. Utilizing your C++programming skills, you will provide the solution to some commonly faced real time problems. Anumber of elements of the course will be used in the exercises for the course project and will helpyou demonstrate your ability to:

Implement a doubly linked list.●

Implement file I/O through streams.●

Implement a template class.●

Use a template with family of classes.●

Copyright© 2002 DigitalThink, Inc. All Rights Reserved.

Storage classes

Module goals

This module introduces you to the concept of storage classes and the different kinds of storageclass qualifiers supported by C++. As the module progresses you will also be introduced to theconcept of namespaces and how they are used in a C++ program. The module will conclude withthe concept of handling unnamed namespaces.

Copyright© 2002 DigitalThink, Inc. All Rights Reserved.

Storage classes

Storage class qualifiers

Every variable or function declared in a program has its own lifetime, which determines theaccessibility of the variable or function throughout the program. The storage class of a variable orfunction determines which part of the program can access it and how long it exists. There aresome existing qualifiers of storage class that provide additional information about storage.

Click the FlipBook button to learn about different storage class qualifiers.

Transcript

Copyright© 2002 DigitalThink, Inc. All Rights Reserved.

Storage class qualifiers

Click the following thumbnails to view the full-sized image.

Constant qualifierThe constant qualifier ensures that the value of a variable remains unchangeduntil the program terminates. The value of a constant variable cannot bemodified once it is declared. This means that a constant variable is onlyavailable in read-only mode throughout the life of the program. Any attempt tomodify the value results in an error message from the compiler. A constantvariable is declared in the following manner:

const int con=100;

The constant variable con is declared and initialized with 100 that will remainunchanged through out the program. You can also use the #define preprocessordirective to specify constants. If you want to assign con with a constant value of100, you can specify the same by:

#define con 100;

However, the use of the #define preprocessor is not recommended. It can lead tofuture program bugs related to typecasting.

Volatile qualifierThe volatile type qualifier indicates that the value in a memory location can bealtered even though nothing in the program code modifies the same. If avariable is declared with volatile keyword then the compiler assumes that, at anypoint in the program, any unknown process can use or modify its value. Forexample, in the case of a program where a particular variable can be accessed bymultiple threads then the concept of volatile variable can be implemented. If avariable is declared only with volatile keyword without specifying the datatypethen int will be the default datatype. A variable can be declared with both constand volatile qualifiers. In this case the variable is accessible in read-only modefrom the same program where it is declared, but for any other process outsidethe program it can be modified.

Mutable qualifierThis is the most advanced qualifier of the storage class family in C++. Thisqualifier ensures that a particular member of a structure can be modified even ifthe variable of the structure is constant. Consider the following sample code:

struct my_data { char name[30]; mutable int age; };

const my_data m={"Johnson",25};

strcpy(m.name,"Steve");//Not allowed, because the variable name //is constant.m.age=m.age+10;//Allowed, because the variable age is declared //with mutable keyword.

So if a variable (age) of a struct (my_data) or class is declared with mutablekeyword, then the variable within the structure can be modified although thevariable of the struct(m) or class is constant.

Copyright© 2002 DigitalThink, Inc. All Rights Reserved.

Storage classes

Functions and storage classes

The functions in C++ have their own storage class. As C++ does not allow you to declare one functionwithin another, all the functions have their own static storage class automatically and they all exist as longas the program is running. In the case of a multiple file program, a function may reside in one particularfile and you can refer to the same from another file.

Click the FlipBook button to learn about different linkages of functions in a C++ program.

Transcript

Copyright© 2002 DigitalThink, Inc. All Rights Reserved.

Storage class qualifiers

Click the following thumbnails to view the full-sized image.

External linkageLinking file with extern keyword: The function declared with extern keywordspecifies that it has external linkage. When a function is declared with externkeyword, then the function is visible from files other than the one in which it isdefined. At the time of compilation when the compiler finds the keyword extern,then it understands that the function is defined in another file, which must becompiled along with the other files of the program. You can declare a functionwith extern keyword in the following way:

extern int calc (int, int);

Internal linkageLinking file with static keyword: The keyword static is used for givinginternal linkage to a file. It ensures that only the current file knows the function.Another function with same name can be created in different file. The staticfunction overrides any external definition--even the library version. Forexample, if you define your own strlen()with static keyword in any one of thefiles of multiple file programming, for the current file the definition of thelibrary version of strlen() will be overloaded with your own definition, and therest of the files will use the library version. The way to declare a function withstatic keyword is as follows:

static int my_function(int x, int y);static int my_function(int x, int y){……..……..}

Copyright© 2002 DigitalThink, Inc. All Rights Reserved.

Storage classes

Language linking

C++ supports a process of linking called language linking, which affects functions only. At the timeof compilation both C and C++ compilers translate the function name into symbolic name forlinking, but the method of translation is different.

Click the FlipBook button to learn about the difference between the processes oflanguage linking in C and C++.

Transcript

Copyright© 2002 DigitalThink, Inc. All Rights Reserved.

Difference between the processes of language linking

Click the following thumbnails to view the full-sized image.

C language linkageAt the time of compilation the compiler needs to distinguish the differentfunctions by different symbolic names. The function names in C being unique,it's very simple to implement this process. For example, if there is a C functioncalled my_function, at the time of compilation the compiler translates thisfunction as _my_function. This C approach of translating a function name into asymbolic name at the time of compilation is called C language linkage.

C++ language linkageIn C++ more than one function can be declared with an identical name due tothe feature of function overloading. So the simple method followed by the Clanguage to give a symbolic name to the function at the time of compilation isnot sufficient in the case of C++. Thus C++ introduces a different process ofgiving a symbolic name to the function, called name mangling. This process isused to look at the type of arguments and number of arguments along with thefunction name when giving a symbolic name to the function. For example, if thefunction is my_function(int,int) then, using the name mangling process, the newsymbolic name will be _my_function_i_i. In the case of my_function(double) itwould be _my_function_d.

Calling a C function from C++It is possible to call a function declared in C from a C++ environment. Forexample, a C function called my_function(int) needs to be called from C++. Butin C the symbolic name will be _ my_function, whereas in C++ it is _my_function_i. To overcome this problem you can use the function prototypeand also indicate which protocol to use when calling the function in thefollowing way:

extern "C" void my_function(int) //using C protocol(C language // linkage) for looking symbolic name

extern "C++" void my_function(int)//using C++ protocol(C++ // language linkage) for looking symbolic name

Copyright© 2002 DigitalThink, Inc. All Rights Reserved.

Storage classes

Dynamic allocation and storage class

C++ storage classes are used for describing memory allocated for variables. It does not go fordynamic memory allocation, which can be done by using new operator. The entire dynamicmemory management process is controlled by new and delete operators and not by scope andlinkage rules. That is why dynamic memory can be allocated from one function and freed fromanother. Storage classes don't directly apply the concept of dynamic memory, but they apply thepointer variables to keep track of dynamic memory. Consider the following statement inside afunction:

int *fees = new int[20];

The above statement ensures that 80 bytes of memory is allocated to fees pointer. As each unit ofint datatype consumes 4 bytes of memory, so 80 bytes is blocked by the mentioned pointer. Thememory will be blocked by the fees pointer until the program where the pointer is declared,terminates or pointer is deleted with delete operator. If you want to retain these 80 bytes ofmemory intact even after the source function terminates, then you need to pass its address toanother function, which is going to retain the same. On the other hand, you can declare the pointerexternally in the following way so that it can be accessed by any function at any point in time:

extern int *fees;

If you declare the *fees variable externally in the above-mentioned way, then it will be accessibleto all the functions and you won't have the headache of passing the address of the same from onefunction to another. So the storage classes and the process of dynamic allocation of memory aretwo completely different processes in C++. The preceding one keeps track of the later one byapplying pointers.

Copyright © 2002 DigitalThink, Inc. All Rights Reserved.

Storage classes

Namespaces

C++ provides a facility to the programmer called namespace for greater control over the scope ofvariables and functions used in a C++ program. A namespace defines a new scope for thevariables and functions, which are referred to as namespace members. The namespace name andthe members of the namespace together determine the uniqueness of a namespace--not the nameof the namespace alone. There may be more than one namespace with an identical name if thenames of the members are different.

Click the FlipBook button to learn about different terms related to namespaces.

Transcript

Copyright© 2002 DigitalThink, Inc. All Rights Reserved.

Different terms related to namespaces

Click the following thumbnails to view the full-sized image.

Declarative regionThis is the region that identifies the area within a program from where themember variable or member function can be accessed. For example, if youdeclare a variable within a function, then the declarative region for the variablewill be the function only. If it is declared outside the function, then thedeclarative region will be the file in which it is declared. So the declarativeregion of a namespace member starts at the point of its declaration.

Code to show declarative region of the variables

#include<iostream.h>#include<stdlib.h>

int p_fund;int main(){ int sal=10650; p_fund=sal*.06; cout<<p_fund; system("pause"); return 0;}

According to the code p_fund and sal are two variables having two differentdeclarative regions. In the case of sal, its accessibility is limited within themain(), because it is declared inside the function. In the case of the p_fundvariable the declarative region is the entire program because it is declared at thetop of the program, so all the functions of the program can access the same atany point in time.

Potential scopeThe potential scope of a variable begins just after at its point of declaration andextends to the end of its declarative region. So the potential scope of a variable ismore limited than the declarative region because a variable can't be referredbefore it is declared. The portion of the program where the variable is actuallyused is called the scope of the variable.

Diagram of potential scope

#include<iostream.h>#include<stdlib.h>int p_fund;int main(){ int sal=10650; p_fund=sal*.06; cout<<p_fund; system("pause"); return 0;}

According to the image, the p_fund variable is declared outside the main() andused within the function. So the potential scope of the variable is the entireprogram because it can be accessed from anywhere in the program--and thescope of the same is limited within two statements(p_fund=sal*.06;cout<<p_fund;)where it is used.

Copyright© 2002 DigitalThink, Inc. All Rights Reserved.

Storage classes

Namespaces and their use

A namespace defines a new scope for the variables declared in a C++ program. Members of anamespace have their own namespace scope within which they are accessible. By using anamespace you can avoid the problem of variable name collisions. The declaration part of thenamespace should not be ended with a semicolon, as it should remain open for any memberinclusion.

Click the FlipBook button to learn about the process of defining and usingnamespace in a C++ program.

Transcript

Copyright© 2002 DigitalThink, Inc. All Rights Reserved.

Defining and using namespace in a C++ program

Click the following thumbnails to view the full-sized image.

Defining a namespaceThe process of defining a namespace is similar to defining a class. First is thenamespace keyword, followed by the identifier (the namespace name), thenfollowed by member declarations enclosed in curly brackets ({..}). A namespacecannot have access specifiers, such as public: or private:. All members of anamespace are public by default, and it cannot have a trailing semicolon.The following example shows the process of declaring a namespace:

namespace jill //A namespace called jill is declared{ int x; //Namespace called jill having only one member //variable x.}

Using a defined namespaceWhile a namespace is declared it can be used in your program. If you want toaccess any of the namespace members into your C++ program you have to usethe using keyword. The process of accessing a namespace member from adefined namespace is as follows:

void main (){ using jill::x; // Referring a member variable x of a // defined namespace jill

cout<<"Enter a number......";

cin>>x; // Read a value into namespace member x // jill::x)}

Complete program using namespace

#include<iostream.h>#include<stdlib.h>

namespace jill //Defining a namespace called jill

{ int x;}

void main (){ using jill::x; //Referring namespace member variable //xof defined namespace jill

cout<<"Enter a number......"; cin>>x; //Read user defined value into jill::x

cout<<" The value stored in namespace variable x is..."<<x<<endl; system("pause");}

Output of a C++ program using namespaceAs the program defined in the previous page, it accepts a user-defined input(1001) in a namespace member variable x and displays the value of x along witha programmer defined string as output.

Copyright© 2002 DigitalThink, Inc. All Rights Reserved.

Storage classes

Nested namespaces

A namespace is a mechanism of C++ that allows the programmer to define the scope of thevariables declared within a program. Namespaces can be nested, which means that at the time ofdeclaring the namespace you can declare one namespace within another.

Click the FlipBook button to learn about the process of declaring and usingnested namespaces in a C++ program.

Transcript

Copyright© 2002 DigitalThink, Inc. All Rights Reserved.

Declaring and using nested namespaces

Click the following thumbnails to view the full-sized image.

Defining nested namespaces

//The following code uses the concept of nested namespace

#include<iostream.h>#include<stdlib.h>

namespace jack // Outer namespace jack is declared.{

int y;

namespace jill // Nested namespace jill is declared //insidethe outer namespace jack. { int x; } //Ending of inner namespace

} //Ending of outer namespace

void main (){

using jack::jill::x; //Referring the variable x of //nested namespacejill through outer namespace jack. using jack::y; // Referring the variable y of outer //namespace jack.

cout<<"Enter first number......"; cin>>x; cout<<"Enter second number......"; cin>>y; cout<<"The value stored in jack namespace variable y is..."<<y<<endl; cout<<"The value stored in jill namespace variable x is..."<<x<<endl; system("pause");}

Output of a C++ program using nested namespacesAs the program defined in the previous page, it accepts two user-defined inputs(1000 & 500) to the namespaces jack and jill respectively and displaying thevalue of outer (jack) and nested (jill) namespaces along with a programmerdefined string as the output of the program.

Using aliases for nested namespacesIn the case of nested namespaces, the example discussed in the previous page ispretty simple in comparison to a real-life environment. The example used onlyone layer of nested namespaces: jill was the nested namespace and jack was theouter namespace. So whenever you have to refer the variable x of the namespacejill, you have to use jack::jill::x . Using an alias can solve the problem ofreferring the nested namespace.The way to define an alias to a nested namespace is as follows:

void main(){ namespace w = jack::jill; //Alias w is declared //for thenamespace jack::jill so that you can //refer the variable x of nestednamespace jill by //w::x directly.

using w::x; //By using the alias w you can refer //x, a variableof a nested namespace jill //directly without referring the outernamespace jack. …………… ……………}

Copyright© 2002 DigitalThink, Inc. All Rights Reserved.

Storage classes

Unnamed namespaces

In general, programmers mention the name of a namespace when they define the same. Thesetypes of namespaces are called named namespaces. But C++ also supports unnamed namespaces.At the time you define a namespace, if you omit the namespace name then the compiler generatesa unique name for the namespace, which remains unique throughout the program. This type ofnamespace is called an unnamed namespace. Declaring a variable in an unnamed namespace is abetter replacement for a static variable declaration. These allow variables and functions to bevisible within an entire translation unit, but not visible externally.

Since an unnamed namespace has no name, you can't explicitly use a using directive to refer tothe variable inside the namespace. But in the case of a nested namespace, if the inner namespaceis unnamed then it can be accessed by referring the outer namespace, which should be a namednamespace.

Click the FlipBook button to learn about the usage of unnamed namespaces.

Transcript

Copyright© 2002 DigitalThink, Inc. All Rights Reserved.

Usage of unnamed namespaces

Click the following thumbnails to view the full-sized image.

Defining unnamed namespaces

#include<iostream.h>#include<stdlib.h>

namespace jack //Named namespace jack is declared.{ int y; namespace // A unnamed nested namespace is declared //inside jack. { int x; }}void main (){ using jack::x;// A variable x, declared in the nested //unnamednamespace is referring through the named //outer namespace jack.

cout<<"Enter first number......"; cin>>x; cout<<"The value stored in nested unnamed namespace variablex is..."<<x<<endl; system("pause");}

Output of a program using an unnamed namespaceAs the program defined in the previous page, it accepts user-defined input (500)to x variable of unnamed namespaces jill. The value of x is shown in the output.

Copyright© 2002 DigitalThink, Inc. All Rights Reserved.

Storage classes

Module wrap-up

In the world of programming you have to declare functions and variables for providing solutionsto real-life problems. Functions or variables have their own lifetime within which they areaccessible. In this module you have also been introduced to the different storage class qualifiersthat determine the accessibility of functions and variables. You have also learned how to createand use namespaces to determine the scope of a variable, function, or class.

Module goals:Describe different kinds of storage class specifiers●

Use storage classes with functions●

Describe language linking●

Describe dynamic allocation and storage class●

Use namespaces●

Describe unnamed namespaces●

Click the Quiz button to check your understanding of storage classes.

Copyright© 2002 DigitalThink, Inc. All Rights Reserved.

Store data in singly linked lists

Module goals

A linked list is a data structure that can grow and shrink, as you need it to. You can add, delete,and access items in it. The most significant feature of link list is that you can allocate to it anamount of memory proportional to the number of items in the list.

Copyright© 2002 DigitalThink, Inc. All Rights Reserved.

Store data in singly linked lists

Linked lists

A linked list is a chain of classes or records. Each record is called a node. Each node contains atleast two members--the record, and the pointer that points to the next item or node in the list.Linked lists are very effective when you are unsure of the number of bytes you actually require. Alinked list is a way of storing data dynamically. It is like having a dynamically allocated stringthat fluctuates in size as the program runs. Whenever you require room for one more node, youjust allocate memory for the node. Then you can link this newly created node to another one thatalready exists in the list. A linked list allows you to insert a node or rearrange existing nodeswithout copying all the remaining elements to new locations.

The following graphic shows the representation of a linked list:

Linked lists and arrays

Linked lists and arrays both store a list of items. In this respect a linked list is similar to an array.However, they are implemented quite differently. An array is a single piece of memory, whereas alinked list contains as many chunks of memory as there are items in the list. Thus, in a linked listif your links get jumbled up, you not only lose a part of the list but also any reference to thoseitems no longer included in the list.

Click the FlipBook button to learn about the advantages and disadvantages oflinked lists over arrays.

Transcript

In a linked list each record must be the instance of the same structure. Youcannot have a record with a char that points to another structure holding ashort, a char array, and a long. For a linked list to work, the records shouldbe instances of the same structure.

Copyright© 2002 DigitalThink, Inc. All Rights Reserved.

Advantages and disadvantages of linked lists over arrays

Click the following thumbnails to view the full-sized image.

Advantages of linked lists over arraysEach node in a linked list can be located anywhere inmemory. Unlike arrays, the nodes in a linked list need not belinear in memory.

You can insert and delete items in a linked list with ease.Inserting items in an array requires you to create room(memory) for the new item. At the same time, deleting itemsin an array requires you to fill up the space created by deletingthe item. For a linked list you simply rearrange the pointersthat are affected by the change.

A linked list allows you to have different-sized nodes in it.●

Disadvantages of linked lists over arraysUnlike arrays, linked lists are quite difficult to sort.●

Locating a particular element in a linked list is difficultcompared to an array. For instance, if you want to locate thehundredth element in a linked list, you have to traverse the listuntil you find the hundredth element.

Copyright© 2002 DigitalThink, Inc. All Rights Reserved.

Store data in singly linked lists

Different types of linked lists

A linked list is a common type of container, consisting of a number of nodes. Each node containsa data field and a pointer to the next node.

There are several types of linked lists. Some of the commonly used ones include:

● Singly linked list

● Doubly linked list

● Circular linked list

Click the FlipBook button to learn about the most widely used linked lists.

Transcript

Copyright© 2002 DigitalThink, Inc. All Rights Reserved.

Most widely used linked lists

Click the following thumbnails to view the full-sized image.

Singly linked listA linked list is a data structure that is built from structures andpointers. It forms a chain of nodes, with pointers representing thelinks of the chain and holding them together. The diagram shownabove represents a singly linked list. These are called singly linkedlists because they point only to the next node and not the previousone.

The above linked list has four nodes in it, each with a link to thenext node in the series. The last node has a link to the special valueNULL. Any pointer can point to it, to show that it is the last link inthe chain. The list also contains another special pointer, called Start,which points to the first link in the chain.

Doubly linked listA doubly linked list has links from each node in both directions. Asyou can see in the above figure, each node in the list has twopointers--one to the next node and the other to the previous one.NULL pointers define the ends of the list. There is no pointer at thestart of the list. Instead, a pointer is present at some position in thelist that can be moved left or right. You need a start pointer in thesingly linked list because after moving from one node to another,you cannot easily move back. Without the start pointer, you willlose track of all the nodes in the list that you have already passed. Ina doubly linked list, you can move the current pointer backwardsand forwards at will.

Circular linked listA circular linked list is a structure where the next pointer of the lastelement points to the first element of the list. The circular linked listdiffers from a singly linked list that the last node does not point to aNULL address. Instead of using the NULL address to test the end ofthe list, you use the beginning address. The beginning of the pointeris where the start pointer points. It will make no difference if youmake the start pointer point to any other node in the list.

Copyright© 2002 DigitalThink, Inc. All Rights Reserved.

Store data in singly linked lists

Singly linked lists

Linked lists are a means to store data within structures. The programmer can automatically createa new place to store data as needed. The programmer writes a struct or class definition thatcontains variables holding information about the class. Each class has a pointer to another class ofits type. Each of the individual classes in the list is called a node. Each pointer points to the nextnode in the list. The pointer in the last node does not point to anything. It should be set to null toprevent it from pointing accidentally to any arbitrary or random location in memory.

A singly linked list can be compared to a train. The programmer always stores the first node of thelist. This is the engine of the train. The pointer is the connector between the cars of the train.

Click the FlipBook button to learn about implementing singly linked list.

Transcript

Copyright© 2002 DigitalThink, Inc. All Rights Reserved.

Implementing singly linked list

Click the following thumbnails to view the full-sized image.

Diagrammatic representation of a singly linked listThe above figure shows four nodes. Each node contains data and a pointer.The start pointer contains the address of the first node. Each next pointer storesthe address of the subsequent node. The pointer in the last node stores a NULLvalue.

Code for creating a node

class node{public: int num; // data node * next; // declaring the next pointer node() // constructor { next = NULL; // assigning NULL value to next pointer }};

The individual unit of a linked list is a node. The above code shows how tocreate a node. The node class contains two members--data and pointer. Thenext pointer created above is assigned a NULL value, as it does not need topoint anywhere right now.

Create a class

class list{private: node* start; // declaring start pointerpublic: list() // constructor { start = NULL; // assigning NULL value to start pointer }};

A list is a chain of nodes. The above code shows how to create a class namedlist. A start pointer to the node class is declared. Initially the start pointer isassigned a NULL value.

Adding a header nodeIt is sometimes useful to add a special start node when implementing a linkedlist class. The start node is a special type of node that does not contain anelement of the list. It is used to help in managing the list. The header node cancontain a pointer to the front node in a singly linked list. Thus it differs from aregular list node.

Copyright© 2002 DigitalThink, Inc. All Rights Reserved.

Store data in singly linked lists

Node addition

Addition of nodes is the most important feature of linked lists. Think of a train. Every time the trainadds a new car, it uses the connectors to add it. This is similar to using the keyword new to create apointer to a new struct or class.

Click the FlipBook button to see how nodes are added in an empty singly linked list.

Transcript

Click the FlipBook button learn how nodes are added when a linked list is not empty.

Transcript

Copyright© 2002 DigitalThink, Inc. All Rights Reserved.

How nodes are added in an empty singly linked list

Click the following thumbnails to view the full-sized image.

Empty lists and unlinked new nodesThe above figure shows an empty linked list. The pointer in the start node does notpoint to any node and contains a NULL value. The new node to be added, insertnode in this case, contains data (num). The pointer contains a NULL value, as itdoes not point to any other node.

Code for adding a node to an empty list

class node{public: int x; node *next; node() { next = NULL; }};

class list{private: node* start;public: list() {start = NULL;} void add(); // Function for adding a node};

void list :: add(){ int num; cout << "Enter an integer: "; cin >> num; node* insert = new node; // Create a new node insert -> x = num; if(start == NULL) // Check if the list is empty start = insert; // Assign address of new node to start node}

The above code shows how a new node can be added to an empty list. At first anew node is created inside the add() function. Then it checks if the list is empty or

not. If the list is found to be empty, the pointer in the start node is assigned theaddress of the new node. The pointer in the new node (insert) continues to have aNULL value.

Linked list representation after node additionThe above figure shows that the new node (insert) has been added to the empty list.

Copyright© 2002 DigitalThink, Inc. All Rights Reserved.

How nodes are added when a linked list is not empty

Click the following thumbnails to view the full-sized image.

A non-empty linked list and new nodeThe above figure shows a linked list that has some existing nodes. The new nodeinsert to be added contains data. The pointer in this node contains a NULL value, asit does not point to any other node.

Code for adding a node in a non-empty linked list

class node{public: int x; node *next; node() {next = NULL;}};

class list{private: node* start;public: list() {start = NULL;} void add();};

void list :: add(){ int num; cout << "Enter an integer: "; cin >> num; node* insert = new node; // Create a new node insert -> x = num; if(start == NULL) // Check if the list is empty start = insert; else { insert -> next = start; // Replace NULL by the address of //first node start = insert; // Assign the address of new node to start }}

In the above code you can find that the new node--insert--is being added at thebeginning of the list. The next pointer of insert is assigned the address of the firstnode. Then the start node is given the address of the new node--insert.

Linked list representation after node additionThe above figure shows how the new node--insert--has been added at the beginningof the list.

Copyright© 2002 DigitalThink, Inc. All Rights Reserved.

Store data in singly linked lists

List traversing

Think about a train. Imagine that the conductor can enter the train only through the engine. He canwalk through the train, down the line, as long as the connector connects the other cars. This isexactly how a program traverses a linked list. The conductor can be compared to a pointer to anode. It first points to the first node. If the first node's next pointer is pointing to something, thenthe pointer will be set to point to the next node. The list is traversed in this fashion. As long asthere is a pointer to something, the traversal continues. Once the NULL pointer is reached, itmeans that there are no more nodes and the end of the list has been reached.

Click the FlipBook button learn about traversing a linked list.

NoteIn the above example you have seen how to add a node at the beginning of a linked list. However,you can also add the node at the end of the list.

Copyright© 2002 DigitalThink, Inc. All Rights Reserved.

Transcript

Traversing a linked list

Click the following thumbnails to view the full-sized image.

Traversing a singly linked list

// singlist.cpp

#include <iostream.h>#include <stdlib.h>

class node{public: int x; node *next; node() {next = NULL;}};

class list{private: node* start;public: list() {start = NULL;} void add(); void display(); // Function for displaying a list};void list :: add(){ int num; cout << "Enter an integer: "; cin >> num; node* insert = new node; insert -> x = num; if(start == NULL) start = insert; else { insert -> next = start; start = insert; }}

void list :: display()

{ node * current = start; // Pointer to the current node while(current! = NULL) // Until the end of list is reached { cout<< current -> x << endl; // Display data in the node current = current -> next; // Move to the next node }}void main(){ list l1; // Create a list object l1.add(); // Add a node to list l1.add(); l1.add(); l1.display(); // Display the list system("PAUSE");}

The above code shows how to traverse a singly linked list. At first apointer--current, in this case--is declared. This pointer is assigned the addressof the first node. After the pointer displays the data on the first node, it isassigned the address of the next node. This process continues unless the NULLpointer is encountered, which shows that the entire list has been traversedsuccessfully.

Output of singlist.cppThe above image shows the output of the singlist.cpp program. From thescreen shot, you can find that the nodes are displayed in the reverse order. Thefirst node that was added, containing a value of 10, is displayed last when thelist is traversed. This is because each new node is added at the beginning of thelist. The last node added becomes the first node of the list.

Copyright© 2002 DigitalThink, Inc. All Rights Reserved.

Store data in singly linked lists

Node deletion

When deleting a node from a linked list, there are three different cases to decide between. Thenode to be deleted can be the first node, a middle node, or the last node of the list. In each of thesecases you must ensure that the link is not snapped when a particular node is deleted.

Click the FlipBook button to learn about deleting a node from a singly linked list.

Now that you have learned how to add, traverse, and delete nodes from a singly linked list youshould be able to work with them comfortably.

Click the FlipBook button to learn the complete code for implementing a singlylinked list.

Transcript

Copyright© 2002 DigitalThink, Inc. All Rights Reserved.

Transcript

Deleting a node from a singly linked list

Click the following thumbnails to view the full-sized image.

Deleting the first node in the listIn this case the node to be deleted is the first node. As this node will be deleted, the address ofthe node next to it should be assigned to the start node. In this case, first the start node shouldbe assigned the address 101, and then the first node should be deleted.

Code for deleting the first node of a linked list

class node{public: int x; node *next; node() {next = NULL;}};

class list{private: node* start;public: list() {start = NULL;} void remove(); // Function for removing the node};

void list :: remove(){ int num; cout << "Enter the number to delete: "; cin >> num; node * del = start; // Declare pointer and assign value if(del-> x == num) // Check if it is the node you want to delete { if(del == start) // Check if it is the first node { start = del -> next; // assign the address of next node to start delete del; // delete the node return; } }}

The above code shows how to delete the current node when it is the first node.

Linked list structure after deleting the first nodeThe above figure shows the structure of the linked list after the first node has been deleted.

Deleting a node from the middle of the list.In this case there is a node before and after the node to be deleted. All you need to do isconnect the previous node to the node after the current node(node to be deleted). First declarea temporary pointer (temp). Then set the temp equal to the node previous to the current oneand the next pointer of current node to the node after the current one.

Code for deleting a node that is in between other nodes

void list :: remove(){ int num; cout << "Enter the number to delete: "; cin >> num; node * del = start; node* temp; // Declare a temporary pointer while(del != NULL) { if(del-> x == num) { if(del == start) { start = del -> next; delete del; return; } else // If the current node is not the first node { temp -> next = del -> next; // Assign the value of next node to temp delete del; // Delete the node return; } } temp = del; // Assign the value of previous node to temp del = del -> next; // Move to next node }}

The above code shows how to delete the current node when it is somewhere in between theothers.

Linked list structure after deleting the middle nodeThe above figure shows the structure of the linked list after the middle node has been deleted.

Deleting the end node of a singly linked listIn this case the node to be deleted is the end node. This is a special case, as a previous nodeexists but no node appears after it to connect to it. You can save the old location of end nodeusing temp. Then set the previous node as the end node. Set the next pointer of this node toNULL, since it now becomes the end node.

Code for deleting an end node

void list :: remove(){ int num; cout << "Enter the number to delete: "; cin >> num; node * del = start; node* temp; while(del != NULL) { if(del->x == num) { if(del == start) // If current node is first node { start = del -> next; delete del; return; } else if ((del->next != NULL)) // If current node is somewhere in //between { temp -> next = del -> next; delete del; return; } else if (del->next == NULL) // If the current node is the last node { temp -> next = NULL; // Assign NULL to the next pointer of last node delete del; // Delete the required node } } temp = del; // Save the old location of end del = del -> next; }}

The above code shows how to delete the current node when it is the last node.

Linked list structure after deleting the end nodeThe above figure shows the structure of the linked list after the last node has been deleted.

Copyright© 2002 DigitalThink, Inc. All Rights Reserved.

Code for implementing a singly linked list

Click the following thumbnails to view the full-sized image.

Complete code for implementing a singly linked list

// singlyLinked.cpp

#include <iostream.h>#include <stdlib.h>

class node // Create a node{ public: int x; node *next; node() { next = NULL; }};

class list // Create a list{private: node* start;public: list() { start = NULL; } void add(); void display(); void remove();};void list :: add() // Add a new node{ int num; cout << "Enter an integer: "; cin >> num; node* insert = new node; insert -> x = num; if(start == NULL) start = insert; else { insert -> next = start; start = insert; }

}

void list :: display() // Traverse the list and display contents{ node * current = start; while(current != NULL) { cout<< current -> x << endl; current = current -> next; }}

void list :: remove() // delete a node{ int num; cout << "Enter the number to delete: "; cin >> num; node * del = start; node* temp; while(del != NULL) { if(del->x == num) { if(del == start) { start = del -> next; delete del; return; } else if ((del->next != NULL)) { temp -> next = del -> next; delete del; return; } else if (del->next == NULL) { temp -> next = NULL; delete del; } } temp = del; del = del -> next; } cout << "Not found" <<endl;}

void main(){ list l1; l1.add(); l1.add(); l1.add(); l1.add();

l1.display(); l1.remove(); l1.display(); system("PAUSE");}

The above code shows the complete implementation of a singly linked list.

Output of singlyLinked.cppThe above screen shot shows the output of a singlyLinked.cpp program.

Copyright© 2002 DigitalThink, Inc. All Rights Reserved.

Store data in singly linked list

Module wrap-up

A linked list is a method of storing data dynamically. Each list consists of a number of nodes.Each node contains a data field and a pointer to the next node. Whenever you need room for onemore node, you simply allocate memory for the node and link with another node that alreadyexists in the list.

Now that you have completed this module, you should be able to:

Describe linked lists●

Define the different types of linked lists●

Implement a single linked list●

Add a node●

Traverse the list●

Delete a node●

Some or all of these terms may be new to you:

list●

node●

container●

Click the Quiz button to check your understanding of linked lists.

Copyright© 2002 DigitalThink, Inc. All Rights Reserved.

Store data in doubly linked lists

Module goals

A doubly linked list is linked a list in which each item has a link to both the previous and nextitem. This allows easy access to list items backwards as well as forwards. Nodes can be deletedwith ease in this type of list. A doubly linked list is also known as a two-way linked list or asymmetrically linked list.

Copyright© 2002 DigitalThink, Inc. All Rights Reserved.

Store data in doubly linked list

Doubly linked list

If you have learned how to work with singly linked lists, it will be easy for you to work withdoubly linked lists. It's like climbing Mt. Everest if you have already climbed the Alps.

Click the FlipBook button to learn about doubly linked lists.

Transcript

Copyright© 2002 DigitalThink, Inc. All Rights Reserved.

Doubly linked lists

Click the following thumbnails to view the full-sized image.

Diagram of a doubly linked listThe individual unit of a linked list is a node. In a doubly linked list, there is a node for eachelement. Each node consists of a part in which the element is stored, and two pointers, onepointing to the next node and the other to the previous one. NULL pointers define the ends ofthe list. There is a link to the beginning of the list called start and a link to the end of the nodecalled the end. With a doubly linked list, you can move the current pointer backwards andforwards at will.

Create a node

class node{ public: int num; // data node * next; // declaring the next pointer node * prev; // declaring the prev pointer node() // constructor { next = prev = NULL; // assigning NULL value to next pointer }};

This code shows how to create a node. The node class contains two members - data andpointer. The next and prev pointers created above are assigned NULL values, as the pointersdo not need to point anywhere at this time.

Create a list class

class list{private: node* start; // declaring start pointer node * end; // declaring end pointerpublic: list() // constructor { start = NULL; // assigning NULL value to start pointer end = NULL; // assigning NULL value to end pointer

}};

A list means a chain of nodes. The above code shows how to create a list class. Start and endpointers to the node class are declared. Initially the start and end pointers are assigned aNULL value.

Copyright© 2002 DigitalThink, Inc. All Rights Reserved.

Store data in doubly linked list

Node addition

A Linked list is a way to dynamically store data. Whenever you need to store more data, you simplyallocate memory for the node and link it with another node that already exists in the list. This processis called node addition.

Click the FlipBook button to see how nodes are added in an empty doubly linked list.

Transcript

Click the FlipBook button to see how nodes are added when a linked list is not empty.

Transcript

Copyright© 2002 DigitalThink, Inc. All Rights Reserved.

Empty doubly linked list

Click the following thumbnails to view the full-sized image.

Empty doubly linked list and unlinked new nodeThe above figure shows an empty linked list. As there are no existing nodes in the list, both the startand end nodes contain NULL value. The new node to be added, insert node, contains data (num1).Both the prev and next pointers contain NULL, as they do not point to any other node.

Adding a node to an empty list

class node{ public: int x; node *next; node *prev; node() { next = NULL; prev = NULL; }};

class list {private: node* start; node* end;public: list() {start = NULL; end = NULL;} void add(); // Function for adding a node};

void list :: add(){ int num; cout << "Enter an integer: "; cin >> num; node* insert = new node; // Create a new node insert -> x = num; if(start == NULL) // Check if the list is empty start = end = insert; // Assign address of new node to start and // end node}

The above code shows how a new node can be added to an empty list. At first a new node is createdinside the add() function. You check to see if the list is empty or not. If the list is empty, the pointer inthe start node is assigned the address of the new node. The pointers in the new node (insert) continueto have NULL value.

Linked list representation after node additionThe image shows that the new node (insert) has been added to the empty list.

Copyright© 2002 DigitalThink, Inc. All Rights Reserved.

Linked list is not empty

Click the following thumbnails to view the full-sized image.

A non-empty linked list and new nodeThe above image shows a linked list that has some existing nodes. The new node insert to beadded contains data. The pointers in this node contain NULL value, as it does not point to anyother node.

Adding a node in a non-empty linked list

class node{public: int x; node *next; node *prev; node() { next = NULL; prev = NULL; }};

class list{private: node* start; node* end;public: list() {start = NULL; end = NULL;} void add(); // Function for adding a node};void list :: add(){ int num; cout << "Enter an integer: "; cin >> num; node* insert = new node; // Create a new node insert -> x = num; if(start == NULL) // Check if the list is empty start = end = insert; // Assign address of new node to start //node

else { // Assign the address of next node to the next pointer of // new node insert -> next = start; // Assign the address of new node to the prev pointer of //next node

insert -> next -> prev = insert; start = insert; }}

In the above code, the new node insert is being added at the beginning of the list. The nextpointer of insert is assigned the address of the first node. The prev pointer of the node next toinsert is assigned the address of insert (new node). Then the start node is given the address ofthe new node insert.

Linked list representation after node additionThe above image shows how the new node insert has been added at the beginning of the list.

Copyright© 2002 DigitalThink, Inc. All Rights Reserved.

Store data in doubly linked list

List traversing

Think about a train. Imagine that the conductor can enter the train through the engine or throughthe caboose. He can walk through the train, as long as the connector connects the cars. This isexactly how a program traverses a linked list. The conductor can be compared as a pointer to anode. The program traverses the list, starting from the initial node and following the next pointersout of each successive node until reaching the NULL pointer. Once the NULL pointer is reached,it means that there are no more nodes and the end of the list has been reached.

Click the FlipBook button to learn about traversing a doubly linked list.

Transcript

Copyright© 2002 DigitalThink, Inc. All Rights Reserved.

Traversing doubly linked list

Click the following thumbnails to view the full-sized image.

Traversing a doubly linked list

// doubleList.cpp

#include <iostream.h>#include <stdlib.h>

class node{ public: int x; node *next; node *prev; node() { next = NULL; prev = NULL; }};

class list{private: node* start; node* end;public: list() {start = NULL; end = NULL;} void add(); // Function for adding a node void display(); // Function for displaying a node};

void list :: add(){ int num; cout << "Enter an integer: "; cin >> num; node* insert = new node; insert -> x = num; if(start == NULL) start = end = insert; else { insert -> next = start;

insert -> next -> prev = insert; start = insert; }}void list :: display(){ node * current = end; // Pointer to the current node while(current != NULL) // Until the beginning of list is //reached { cout<< current -> x << endl; // Display data in the node current = current-> prev; // Move to the previous node }}void main(){ list l1; // Create a list object l1.add(); // Add a node to list l1.add(); l1.add(); cout<< endl; l1.display(); // Display the list system("PAUSE");}

The above code shows how to traverse a doubly linked list. At first a pointer current isdeclared. This pointer is assigned the address of the last node. After the pointer displaysthe data on the last node, it is assigned the address of the previous node. This processcontinues unless the NULL pointer is encountered, indicating that the entire list has beentraversed successfully.

Output of doubleList.cppThe above screen shot shows the output of the doubleList.cpp program. The nodes aredisplayed in the order in which they were added. In the above example you learned toadd a node at the beginning of the linked list. However, you can also add the node at theend of the list.

Copyright© 2002 DigitalThink, Inc. All Rights Reserved.

Store data in doubly linked list

Node deletion

When deleting a node from a doubly linked list, there are three different situations to decide from.The node to be deleted is the first node, a middle node, or the last node. In each of these cases youmust be sure that the link between the other nodes in the list is maintained when a particular nodeis deleted.

Click the FlipBook button to learn about deleting a node from a doubly linked list.

Transcript

Copyright© 2002 DigitalThink, Inc. All Rights Reserved.

Deleting a node from a doubly linked list

Click the following thumbnails to view the full-sized image.

Deleting the first node in the listIn the above case the node to be deleted is the first node. As this node will be deleted,the address of the node next to it should be assigned to the start node. The start nodeshould be assigned the address 202. The prev pointer of the next node (with theaddress 202) should be assigned NULL value, as this node will become the first node.Then the first node should be deleted.

Code for deleting the first node of a doubly linked list

class node{ public: int x; node *next; node *prev; node() { next = NULL; prev = NULL; }};

class list{private: node* start; node* end;public: list() {start = NULL; end = NULL;} void remove(); // Function for removing the node};

void list :: remove(){ int num; cout << "Enter the number you want to delete: "; cin >> num; node * current = start; // Declare pointer and assign value if(current->x ==num) // Check if it is the node you want to //delete {

if(current == start) // Check if it is the first node { current->next->prev = NULL; // Assign NULL value to prev //pointer start = current -> next; //Assign the address of next //node to start delete current; // Delete the node return; } }}

The above code shows how to delete the current node when it is the first node

Doubly linked list structure after removing the first nodeThe above image shows the structure of the linked list after the first node has beenremoved.

Deleting a node from the middle of the listIn the above case there is a node before and after the node to be deleted. All you needto do is connect the previous node to the node after the current node (node to bedeleted).

Code for deleting a node that is in between other nodes

void list :: remove(){ int num; cout << "Enter the number to delete: "; cin >> num; node * current = start; while(current != NULL) { if(current -> x == num) { if(current == start) { current -> next -> prev = NULL; start = current -> next; delete current; return; }

// If the current node is somewhere in between else if ((current != start) && (current != end)) { current -> prev -> next = current -> next; current -> next -> prev = current -> prev; delete current; // Delete the node return; } }current = current -> next; // Move to next node }}

The above code shows how to delete the current node when it is in between nodes.

Linked list structure after removing the middle nodeThe above image shows the structure of the linked list after the middle node has beenremoved.

Deleting the last node of a doubly linked listIn this case the node to be deleted is the last node. This is a special case, as a previousnode exists but there is no node after it to connect it to. Assign NULL value to thenext pointer of the previous node. Then assign the address of the previous node to endso that it becomes the last node.

Code for deleting the last node of a doubly linked list

void list :: remove(){ int num; cout << "Enter the number to delete: "; cin >> num; node * current = start; while(current != NULL) { if(current -> x == num) { if(current == start) { current -> next -> prev = NULL; start = current -> next; delete current; return; } else if ((current != start) && (current != end))

{ current -> prev -> next = current -> next; current -> next -> prev = current -> prev; delete current; return; } // If the current node is the last node else if (current == end) { // Assign NULL value to next pointer of previous node current ->prev -> next = NULL; // Assign the address of previous node to end so that // it becomesthe last node end = current -> prev; delete current; return; } }current = current -> next; // Move to next node }}

The above code shows how to delete the current node when it is the last node.

Linked list structure after removing the last nodeThe above image shows the structure of the linked list after the last node has beenremoved.

Copyright© 2002 DigitalThink, Inc. All Rights Reserved.

Store data in doubly linked list

Doubly linked list implementation

You have learned how to add, traverse, and delete nodes from a doubly linked list.

Click the FlipBook button to see the complete code for implementing a doubly linked list.

Transcript

Copyright© 2002 DigitalThink, Inc. All Rights Reserved.

Implementing a doubly linked list

Click the following thumbnails to view the full-sized image.

Complete code for implementing a doubly linked list

// doublyLinked.cpp

#include <iostream.h>#include <stdlib.h>

class node{ public: int x; node *next; node *prev; // Create a node

node() { next = NULL; prev = NULL; }};

class list{ private: node* start; node* end; // Create a list public: list() {start = NULL; end = NULL;} void add(); void display(); void remove(); };

void list :: add(){ int num; cout << "Enter an integer: "; cin >> num; node* insert = new node; // Add a new node insert -> x = num; if(start == NULL)

start = end = insert; else { insert -> next = start; insert -> next -> prev = insert; start = insert; }}void list :: display(){ node * current = end; // Traverse the list and display //contents while(current != NULL) { cout<< current -> x << endl; current = current -> prev; } }

void list :: remove(){ int num; cout << "Enter the number to delete: "; cin >> num; node * current = start; while(current != NULL) // Delete a node { if(current -> x == num) { if(current == start) { current -> next -> prev = NULL; start = current -> next; delete current; return; } else if ((current != start) && (current != end)) { current -> prev -> next = current -> next; current -> next -> prev = current -> prev; delete current; return; } else if (current == end) { current -> prev -> next = NULL; end = current -> prev; delete current; return; } }

current = current -> next; // Move to next node }}void main(){ list l1; l1.add(); l1.add(); l1.add(); l1.add(); cout<< endl; l1.display(); l1.remove(); cout<< endl; l1.display(); system("PAUSE");}

The above code shows the complete implementation of a doubly linked list.

Output of doublyLinked.cppThe above screen shot shows the output of a doublyLinked.cpp program.

Copyright© 2002 DigitalThink, Inc. All Rights Reserved.

Store data in double linked lists

Module wrap-up

The doubly linked list is an efficient data structure if you need to traverse the elements on a list inboth directions. You can insert new elements anywhere in the list and efficiently delete anyelement from the list. A doubly linked list consists of a number of nodes, each containing exactlyone element. Some of the functions operate directly on the elements, while some manipulatenodes.

Now that you have completed this module you can:

Describe a doubly linked list●

Add a node●

Traverse the list●

Delete a node●

Implement a doubly linked list●

Click the Quiz button to check your understanding of doubly linked lists.

Copyright© 2002 DigitalThink, Inc. All Rights Reserved.

Debugging and exception handling

Module goals

In the world of programming there are two types of situations: expected and unexpected. In C++an exception is a situation that is unusual and unexpected. When programming in C++, youshould anticipate abnormal situations caused by users entering wrong information, withunpredictable results. This module covers C++ mechanisms for handling exceptions.

Copyright© 2002 DigitalThink, Inc. All Rights Reserved.

Debugging and exception handling

Code debugging

A program is a sequential flow of instructions. When it executes, the instructions written inside itexecute in the same sequence as they were written in the program. With program debugging youcan easily follow the flow of the program while it is executing. In the Bloodshed compiler beforedebugging a program, you should perform the following steps:

Compile the program.1.

Mark the starting point of debugging by putting a toggle breakpoint in a particularstatement.

2.

Click the Simulation button to practice debugging code in a C++ program.

Transcript

Click the FlipBook button to learn about the utility of the Step Over and Step Into buttons.

Copyright© 2002 DigitalThink, Inc. All Rights Reserved.

Transcript

Debugging code in a C++ program

Debugging code in a C++ program

A compiled C++ code is written for you. This is a prerequisite for debugging C++ code ina bloodshed environment. The cursor is already placed at the statement where thedebugging will start. Click the Debug menu.

1.

Click the Toggle Breakpoint option to mark the current statement as the starting point ofthe debugging process.

2.

The statement where the cursor was placed is marked as breakpoint, from which point thedebugging will start. Click the Debug menu to start the debugging process.

3.

Click the Debug option to invoke the debugging window.4.

A debug window will open automatically; click the Next Step button on the left side of thescreen.

5.

The control is now on the line where the debugging started (accepting user input with cinoperator). Click the Next Step button to execute the statement.

6.

After executing the statement, click the debugging window icon from the status bar toinvoke the debugging window. This icon is highlighted in red for you.

7.

Click anywhere in the debugging window. A number will be entered for you.8.

Number 25 has been entered for you. Press Enter to continue.9.

The code window will opened again, and the pointer will be placed in the next line, whichdisplays the statement "Square of the number is…". Click Next Step to execute thisstatement.

10.

After executing the previous line the pointer is placed on the next statement," Summationof the number is...". To view the effects of execution, click the debugger window icon fromthe status bar. This icon is highlighted in red for you.

11.

The debugger window displays, along with the square of the number. Click the Next Stepbutton to execute the selected statement. This will display the summation and invoke thecode window.

12.

To view the effect of execution and invoke the debugger window, click the debuggerwindow icon from the status bar.

13.

The debugger window displays both the summation and the square of the number. Clickthe Next Step button to invoke the code window.

14.

The pointer is now placed at the last line of the program. There are no more lines toexecute. To execute the current line, click the Next Step button.

15.

To invoke the debugger window and view the execution of the last line of the program,click the debugger window icon from the status bar.

16.

The usual concluding message is displayed, validating that you have successfullydebugged the program. Click the Close button to exit the Simulation.

17.

Copyright© 2002 DigitalThink, Inc. All Rights Reserved.

Utility of the Step Over and Step Into buttons

Click the following thumbnails to view the full-sized image.

Utility of the Step Over buttonWhen debugging a program, you are usually debugging multiple statements. Ifyou continue your debugging process by clicking the Next Step button, then theflow of control will be placed on each statement. If you want to execute all thestatements, then click the Step Over button. Clicking the Step Over buttonplaces the flow of control at the last statement of the program after executing allthe intermediate statements successfully.

Logical flow of a program when the Step Over button is pressedIn this image, a debugging process is initiated from Statement 1. When thecontrol reaches Statement 2, the Step Over button is clicked. As the Step Overbutton is clicked, control is placed on the last statement of the program afterexecuting the intermediate statements (3 and 4) successfully.

Utility of Step Into buttonWhen debugging a program, you are actually debugging multiple statements. Ifyou continue the debugging process by clicking the Next Step button, the flowof control will be placed on each statement and each statement will be executed.If you don't want to place the control on the statements or execute them, thenclick the Step Into button. Clicking the Step Into button places the flow ofcontrol on the last statement of the program without executing the intermediatestatements.

Logical flow of program when Step Into button is pressedIn the image, the debugging process is initiated from Statement 1. When thecontrol reaches Statement 2, the Step Into button is clicked. As the Step Intobutton is clicked, control is placed on the last statement of the program withoutexecuting the intermediate statements.

Copyright© 2002 DigitalThink, Inc. All Rights Reserved.

Debugging and exception handling

Exception handling

As a programmer you should code your C++ program in such a way that it can handle anyunexpected situation upon execution. You need to be able to anticipate abnormal behavior caused bya user entering wrong information, with unpredictable results. Dealing with a program's abnormalbehavior is called exception handling.

Click the View Image button to see an explanation of the exception handling process.

Copyright© 2002 DigitalThink, Inc. All Rights Reserved.

Debugging and exception handling

The mechanism of exception handling

The process of dealing with program's unpredicted behavior at the time of its execution is calledexception handling in C++. If you want to implement exception handling in your program, thenyou should follow a specified structure accompanied by certain keywords related to exceptionhandling. The three keywords related to exception handling are try, throw, and catch.

Click the FlipBook button to learn about the structure and different keywordsrelated to exception handling.

Transcript

Copyright© 2002 DigitalThink, Inc. All Rights Reserved.

Structure and keywords related to exception handling

Click the following thumbnails to view the full-sized image.

Logical structure of exception handling in C++

Statement 1;

......try{ // Initiating the try block

Statement 2; // Putting the statement inside // try block, which may throw // exception

Throw Exception (); // Statement used for throwing // exception

} catch (Exception e) // Catch block initiates the // exception handling section //justafter the try block ends

{

Statement; // Statement inside the catch // block will be executed if the // exception is caught properly.

Try blockThe exception handling process begins with the try block. As a programmer youshould anticipate which statements might behave unexpectedly and keep theminside the try block.

Statements within this block will be inside curly brackets;, for example, "try{statements}". This tells the compiler that you anticipate that the statementsinside the block might behave unexpectedly. There must be at least one catchblock immediately following the try block. The main responsibility of the tryblock is to pass over control to the appropriate handler if the programmerdeclares it, otherwise it will be passed to the operating system to handle.

Throw keywordThrow is the keyword that throws or raises the exception. It must be inside a tryblock. When executed, the control passes directly to the immediate catch blockwithout executing the rest of the statements inside the try block. You can placeyour condition with an 'if' statement to specify when the exception actually willbe thrown.

Catch blockThe Catch block is the final block of the exception handling structure, where theexception is actually handled. The try block must immediately precede the catchblock and there must not be any statement between these two blocks. Like thetry block, the statements of the catch block are also written inside curly brackets({…}). If the raised exception is properly caught, then only the statementswritten inside the catch block will be executed. You have to write yourwhat-to-do statement inside the catch block to determine the flow of yourprogram.

Copyright© 2002 DigitalThink, Inc. All Rights Reserved.

Debugging and exception handling

Exception handling demonstration

To implement the exception-handling mechanism within your program you have to use thespecified structure for exception handling. The defined structure consists of three keywords: try,throw, and catch.

Click the FlipBook button to learn how to implement an exception handlingmechanism in a C++ program.

Transcript

Copyright© 2002 DigitalThink, Inc. All Rights Reserved.

Exception handling mechanism in a C++ program

Click the following thumbnails to view the full-sized image.

Demonstrating exception handling

//Code of a C++ program with implemented exception handling mechanism

#include <iostream>#include <stdlib.h>

int main(){ int salary; int tax;

cout << "Enter Employee's Salary amount: ";

try //Beginning of try block, the statements inside the // block maythrow exception { cin >> salary;

if(salary <= 0) //Condition for throwing exception

throw 1; // Exception thrown after satisfying the // previouscondition

tax=salary*.15; cout << "\nEmployee's due amount of tax is:: " << tax << "\n\n";

}catch(const int n)//Beginning of catch block to handle the //exception thrown by try block {

cout<<" Employee's salary cannot be negative or zero:: Exception thrown and successfully handled "<<endl; }

system("pause");return 0;}

The above program is prompting the user to enter a salary amount, for which it willcalculate the amount of tax owed. If a user enters 0, then the exception will be thrownand handled by the specified handler.

Output of a C++ program using the exception handling mechanismBecause the user entered 0 as salary amount, an exception is thrown and handledsuccessfully by the program written in the previous page.

Copyright© 2002 DigitalThink, Inc. All Rights Reserved.

Debugging and Exception Handling

Nested exception handling

Nested exception is the mechanism of handling one exception within another. The structure of theexception handling process is initiated with a try block and immediately followed by a catchblock. C++ also supports nested exception handling when there is an inner try…catch blockwithin an outer try…catch block.

Click the FlipBook button to learn about implementing nested exception handling.

Transcript

Copyright© 2002 DigitalThink, Inc. All Rights Reserved.

Implementing nested exception handling

Click the following thumbnails to view the full-sized image.

C++ code with the concept of nested exception

#include <iostream>#include <stdlib.h>

int main(){ int salary; int tax;

cout << "Enter Employee's Salary amount: ";

try //Outer exception handling block in initiated. { cin >> salary;

if(salary <= 0) throw 1;

try{ //Inner exception block is initiated within an outer //exceptionblock

if(salary>=75000) throw "no";//Exception is thrown from inner block if the //stated condition satisfies

}catch(const char *m) //catch block related to inner try //block { cout<<"Salary is too much,Tax amount may be shocking"; } tax=salary*.15; cout << "\nEmployee's amount of tax due is:: " << tax <<"\n\n";

}catch(const int n) //Catch block related to outer try block { cout<<"Employee's salary cannot be negative or zero::Exception thrown and successfully handled"<<endl;}

system("pause");return 0;

}

There are two conditions mentioned for throwing an exception with the conceptof nested exception. If the entered amount of salary is less than or equals to 0 theouter exception will be thrown, and if it is greater than 75000 the inner one willbe thrown.

Output of a C++ program using nested exceptionThe user enters 90000 as the amount of salary. Due to the specified condition,the inner exception will be thrown. Along with the calculated tax amount, themessage will also be displayed because the inner exception is thrown andhandled.

Copyright© 2002 DigitalThink, Inc. All Rights Reserved.

Debugging and exception handling

Multiple try and catch blocks

As per the defined structure of exception handling, a catch block should immediately follow a tryblock. But sometimes it is required to use multiple try and catch blocks within a particularprogram. In a C++ program you can use multiple try and catch blocks. A try block can befollowed by multiple catch blocks, but a catch block cannot handle an exception thrown frommultiple try blocks. A catch block is always associated with only one try block.

Click the MouseOver button to learn how to use multiple try and catch blockswithin a program.

Transcript

Copyright© 2002 DigitalThink, Inc. All Rights Reserved.

Multiple try and catch blocks within a program

Copyright© 2002 DigitalThink, Inc. All Rights Reserved.

Debugging and exception handling

Unhandled exceptions

According to the predefined structure of exception handling, an exception will be thrown from atry block and handled by a catch block defined just after the try block. In some cases it is verydifficult to predict unexpected situations properly and define an appropriate handler for them.When an exception is thrown in such a case, it is handled by the Operating System instead of by apredefined handler. This type of exception is called an unhandled exception.

If an exception is thrown and there is no handler for the exception, then an Operating Systemdefined function called terminate is executed. This function executes abort(), another systemdefined function, and the program is terminated abnormally.

Click the View Image button to see the logical flow of a program when anexception is not handled.

Copyright© 2002 DigitalThink, Inc. All Rights Reserved.

Debugging and exception handling

Module wrap-up

As a C++ programmer, debugging programs and anticipating unexpected situations are crucialtasks. They help you understand the logical flow of a program. In this module you learned how totackle unexpected situations, which might interrupt the normal flow of your program, throughexception handling.

Now that you have completed this module, you should be able to:

Debug a C++ program●

Describe the mechanism of exception handling●

Demonstrate exception handling in C++●

Describe unhandled and unnamed exceptions●

Some or all of these terms may be new to you:

Toggle breakpoint●

Click the Quiz button to check your understanding of debugging and

exception handling.

Copyright© 2002 DigitalThink, Inc. All Rights Reserved.

Data transmission through streams

Module goals

The inputs made by users in a C++ program are volatile in nature, meaning they exist as long theprogram runs. But in some cases user inputs are required for future retrieval. The input/outputoperations of C++ help to store the user input permanently so that they are accessible even afterthe program execution. This module will introduce you to the different modes of performing I/Ooperations and to the concept of streams and buffers, which are essential to successfullycompleting the I/O process.

Copyright© 2002 DigitalThink, Inc. All Rights Reserved.

Data transmission through streams

File I/O

A simple C++ program accepts user input, processes the same within the program, and remainsaccessible until the program ends its execution process. These inputs are no longer accessible afterthe program completes execution. C++ provides you the facility of file I/O to store user input on ahard disk as a file. This ensures the accessibility of the input even after the program completes itsexecution process. A C++ program reads data from the disk and writes data into the disk with thehelp of Streams.

Click the View Image button to enhance your knowledge of how a C++ programmanages file I/O through streams.

The data source for a C++ program can be of three types--keyboards, files, or nother programs.The data target can also be of three types--programs, files or a monitor. A stream works as anintermediate layer between a program and a data source or target.

Copyright© 2002 DigitalThink, Inc. All Rights Reserved.

Data transmission through streams

Stream class hierarchy

A stream is a flow of data that passes from a C++ program to a hard disk and vice versa. C++ provides a number ofpredefined classes, which represent different kinds of data flow. Each stream is associated with a particular class,which contains member functions and data definitions for dealing with a particular data flow. The stream classes arearranged in a specific hierarchy.

Click the View Image button to see the hierarchy in which the predefined stream classes are arranged.

According to the specified hierarchy, ios is the base class. This class has two derived classes: ostream and istream.Among these classes ostream contains the methods and data definition that are required for stream output, and istreamcontains the methods and data definitions that are required for stream input. In most of the C++ program, iostreamclass is used--a derived class of ostream and istream.

Copyright© 2002 DigitalThink, Inc. All Rights Reserved.

Data transmission through streams

Stream buffering

A C++ program treats an input or output as stream of bytes . At the time of input, a programextracts bytes from an input stream, and during output it inserts bytes into the output stream.Usually the buffer handles the input and output of bytes more efficiently for a program. It worksas a temporary storage unit to maintain the balance between the byte processing speed of a deviceand a program. Generally a device driver transfers bytes in a block (512 bytes or more) at a pointin time, and a program processes one byte. The buffer terminates any problem that may arise dueto this mismatching of speed.

Click the View Image button to see how the buffer works.

The image depicts how a stream of data flows from a device to a buffer (block by block) and thenfrom the buffer to a program (byte by byte). But a buffer can also be used to store data in a devicefrom a program. The process of writing a block of data from a buffer to a device is called flushingthe buffer.

Copyright© 2002 DigitalThink, Inc. All Rights Reserved.

Data transmission through streams

String I/O

Using a C++ program you can very easily perform certain string related input and outputoperations. There are some pre-defined C++ classes that help you to create your own OperatingSystem file. You can use this to permanently write strings of data onto a device (usually a harddisk) and read data from the device as required.

Click the FlipBook button to learn about reading and writing operations on a file.

Transcript

Copyright© 2002 DigitalThink, Inc. All Rights Reserved.

Reading and writing operations on a file

Click the following thumbnails to view the full-sized image.

Writing data into a file

//Writing data into a File:

#include <fstream.h> //Header file included for file //relatedfunctions#include <stdlib.h>

void main(){

ofstream ofile("TEST.txt"); //Creating an object(ofile)of //ofstream class // to create a text //file(TEST.txt)for output.

ofile<<"Hi Johnson\n"; //User defined string storing //into file through //object of ofstream class

ofile<<"Have a nice day"<<endl;

cout<<"File created successfully"<<endl;//Message //ensuring successful creation //of thefile.

system("PAUSE");

}

In the above program, ofile is an object of the ofstream class. It calls theconstructor of the ofstream class to create an Operating System file namedTEST.txt.Then a programmer-defined string ("Have a nice day ") is insertedinto TEST.txt file with the help of the ofile object and '<<' extraction operator.

Reading data from a file

// Reading data from a file:

#include <fstream.h>#include <stdlib.h>

void main(){const int mx=80;char nm[mx]; // A variable is declared to store the //datafrom the file

ifstream ifile("TEST.txt"); // Set the file as source of // reading data

while(ifile) //To read till the end of the file. { ifile.getline(nm,mx); //Storing data into defined // variable cout<<nm<<endl; //Displaying data from the file line //by line }

system("PAUSE");

}

In the above program ifile is an object of the ifstream class. It calls theconstructor of the class to set an Operating System file named TEST.txt as thesource of reading data. Within a loop the reading process will go on until theend of the files is reached.

Output of the above programThis output shows the content of the file TEST.txt, which was populated by theprogram mentioned in the first page of this FlipBook.

Copyright© 2002 DigitalThink, Inc. All Rights Reserved.

Data transmission through streams

Character I/O

In a C++ program sometimes you're required to perform character by character data insertion intoa file and to fetch data from the file in the same manner. For character input and output, twosystem-defined functions are required, put()and get(). Put is required for inserting data into thefile and get for fetching data.

Click the FlipBook button to learn how to insert and fetch data to and from a file.

Transcript

Copyright© 2002 DigitalThink, Inc. All Rights Reserved.

Insert and fetch data to and from a file

Click the following thumbnails to view the full-sized image.

Character by character file output

//Character by character file output:

#include <fstream.h> #include <stdlib.h>

void main(){

char str[80]="Good morning Johnson. How are you?";

ofstream ofile("JOHN.txt");

for(int x=0;x<strlen(str);x++) { ofile.put(str[x]);//Fetching characters one-by-one from //the initialized //string str and inserting into file // JOHN.txt. }

cout<<"File created successfully"<<end1;

system("PAUSE");

}

The above program inserts the initialized string (str) into the specified file, called"JOHN.txt", character by character.

Character by character file input

//Character by character file input:

#include <fstream.h>#include <stdlib.h>

void main(){

char str; ifstream ifile("JOHN.txt");

while(ifile) { ifile.get(str);//Fetching data characters by //character from the file JOHN.txt cout<<str<<end1;//Displaying each character //in a separate line }

system("PAUSE");

}

This program fetches data from the file JOHN.txt character by character and displayseach character in a separate line.

Output of the character by character file inputEach character fetched from JOHN.txt file is displayed in separate line.

Copyright© 2002 DigitalThink, Inc. All Rights Reserved.

Data transmission through streams

Object I/O

An object in C++ is nothing but the combination of member functions and data. Sometimes youare required to perform input/output operations through objects. Just like strings and characters,objects are also used for input and output operations. The following example deals with theprocess of how the objects are used for reading and writing data from and into a file.

Click the MouseOver button to go through a program where an object is used forreading and writing data from and into a file.

Transcript

Copyright© 2002 DigitalThink, Inc. All Rights Reserved.

Object is used for reading and writing

Copyright© 2002 DigitalThink, Inc. All Rights Reserved.

Data transmission through streams

Input/Output with multiple objects

In the world of real-life programming, data insertion into a file and data extraction from a file isone of the most frequently performed tasks. In most cases only one object is used to perform thisactivity. C++ supports inserting data into a file through multiple objects. Users can use as manyobjects as they want to insert data into a file.

Click the FlipBook button to learn the process of file I/O using multiple objects.

Transcript

Copyright© 2002 DigitalThink, Inc. All Rights Reserved.

File I/O using multiple objects

Click the following thumbnails to view the full-sized image.

File I/O using multiple objects

//File I/O through multiple objects

#include <fstream.h> #include <stdlib.h>

class empl{ private:

char name[20]; int age;

public: void getdata() { cout<<"Enter your name......"; cin>>name; }

void showdata() { cout<<name<<endl; } }; void main(){ char ch; empl el; fstream file;

file.open("EMPLOYEE.dat",ios::app); do { cout<<"\nEnter Employee information:"<<endl; el.getdata(); file.write((char *)&el,sizeof(el)); cout<<"Enter another person..(y/n):"; cin>>ch; }while(ch=='y');

file.close();

file.open("EMPLOYEE.dat",ios::in);

cout<<"\n\n\nList of existing Employees"<<endl; file.read((char *)&el,sizeof(el)); while(!file.eof()) { el.showdata(); file.read((char *)&el,sizeof(el)); } system("pause");}

The above program first accepts as many employee names as the user wants. Then itdisplays the entered names.

Output of C++ program showing file I/O using multiple objectsIn the above program, two employee names were inserted: Johnson and Robinson. Theoutput shows the names under the heading "List of existing Employees."

Copyright© 2002 DigitalThink, Inc. All Rights Reserved.

Data transmission using streams

Module wrap-up

You've seen how streams are used to store user input into a device, usually a hard disk, to save itpermanently for future retrieval.

Now that you have completed this module you should be able to:

Use streams●

Describe buffers●

Describe I/O using strings●

Describe character by character I/O●

Describe I/O using objects●

Describe I/O using multiple objects●

Some or all of these terms may be new to you:

streams●

bytes●

buffer●

Click the Quiz button to check your understanding of streams, buffers, and

Copyright© 2002 DigitalThink, Inc. All Rights Reserved.

different modes of performing I/O in C++.

Work with templates

Module goals

Templates are a way to specify generic code in C++. You can place your code inside a templatewithout considering the data type. While you are going to refer the code defined inside thetemplate from your program, you have to pass the data type as the parameter. This module willintroduce you to the process of creating your own template and referring it from your program.

Copyright© 2002 DigitalThink, Inc. All Rights Reserved.

Work with templates

Template

The template in C++ works as a prototype that, once created, can be used as many times as the programmer wants.Once a template is defined, multiple programs can refer to it. The template actually works as the header file in C++.

You can define your own template in any text editor environment and save it with the .h extension in the same locationwhere you are going to save your .cpp file. You have to include the .h file with the '#include' preprocessor directivewithin your .cpp file to reuse the class or function defined within the template. Templates can be of two types: classtemplates and function templates.

Now click the View Image button to learn about the logical flow of a program when a template is used.

Click here to learn more.

Copyright© 2002 DigitalThink, Inc. All Rights Reserved.

Work with templates

Function template

A function template is used for creating generic functions in C++. It can be called from any C++ program with parametersof any valid data type and can return a value of the same data type as the argument. At the time of defining the function ina template, the data type of parameters and return value is not required, only the function body and number of parametersneeds to be mentioned. All the parameters and the return type must be of the same data type in a function template.

Click the FlipBook button to learn about how to create a function template and refer it from your program.

Transcript

Copyright© 2002 DigitalThink, Inc. All Rights Reserved.

Create a function template and refer it from your program

Click the following thumbnails to view the full-sized image.

Creating a function template

//Creating a function template:// template_function.h -- Name of the template file saved with .h extension

template <class b> //Defining a function template with an identifier 'b'

b add(b x, b y) /*function 'add' is defined which is just mentioning the number of parameters( x and y) not the datatypes. */

{ return x + y; //Body of 'add' function. Returning a value of unknown datatype}

A function template is created with identifier 'b'. The function within the template called'add' is created with two parameters (x and y) and one return value, but the data typesare not mentioned within the template. The above file is created using Notepad andsaved as 'template_function_1.h'.

C++ program using a function template

//C++ program referring function template#include <iostream>#include <stdlib.h>#include "template_function.h"

void main(){

int tot=add<int>(25,84); /*Invoking the function from template andspecifying the datatype as int */cout<<"Output of int Datatype..."<<tot<<endl;

double tot1=add<double>(25.36,45.79); /*Invoking the function fromtemplate and specifying the datatype as double */

cout<<"Output of double Dataype..."<<tot1<<endl;

system("PAUSE");

}

In the above code, the add function of the function template is called two times. The firsttime, it is called with int data type with the values 25 and 84, and the second time it iscalled with double data type with the values 25.36 and 45.79 respectively.

Output of a program using a function templateThe two different sets of outputs are displayed, as the function 'add' was called twice.You can call the same function as many times as you want within a program, or it can becalled from multiple programs.

Copyright© 2002 DigitalThink, Inc. All Rights Reserved.

Work with templates

Template class

A template class is used to create a generic class that can be referred by any program after thesuccessful creation of the template. Once the template class is created, members declared in thepublic section of the class are accessible to any program referring to the template.

Click the FlipBook button to learn how to create a class template and refer it fromyour program.

Transcript

The template class also has its own access specifiers, private and public. The member functionsdeclared inside the private section of the template class cannot be referred from a program,because the functions are not accessible from outside the template class.

Copyright© 2002 DigitalThink, Inc. All Rights Reserved.

Create a class template and refer it from your program

Click the following thumbnails to view the full-sized image.

Creating a class template

//Creating a class template://Template_class.h---Name of the template file saved with //.h extension

template <class T>

class myclass{ public:

myclass(){ };

T add(T a, T b)

{

return a + b;

}

T multiply(T a, T b)

{

return a * b; }

};

A class template is created with identifier 'T'. The functions within the class called'add' and 'multiply' are created in the public section of the class. The above file iscreated using Notepad and saved as 'template_class.h'.

C++ program using a class template

//C++ program referring class template:

#include <iostream.h>#include <stdlib.h>#include "template_class.h" //Class template is referred

void main(){ myclass<int> mcl; /*Object of the template class is declared bypassing int datatype as parameter*/

int z=mcl.add(25,36);//int type of arguments are //passingto 'add' function cout<<z<<endl;

myclass<double> mcl1; /*Object of the template class is declared bypassing double datatype as parameter*/

double z1=mcl1.add(32.24,65.94); /*double type of arguments arepassing to 'multiply' function*/

cout<<z1<<endl;

system("PAUSE");

}

In the above code, two instances of myclass are declared, mcl as int data type andmcl1 as double data type. In the former instance the add function is called withtwo integer arguments, and in the later instance the same function is called withtwo double parameters.

Output of a program using class templateThe two different sets of outputs are displayed, as the function 'add' was calledtwice. You can call the same function as many times as you want within aprogram by declaring multiple objects of the same class with different parametersof different data type.

Copyright© 2002 DigitalThink, Inc. All Rights Reserved.

Work with templates

Template with a family of classes

A significant feature regarding the template class is that if a C++ program has multiple classes, then from all these classesyou can refer the particular class that is declared inside the template. So a template can be used with a family of classes foryour C++ program.

Click the FlipBook button to learn how to use the template class with a family of classes in a C++ program.

Transcript

Copyright© 2002 DigitalThink, Inc. All Rights Reserved.

Template with a family of classes

Click the following thumbnails to view the full-sized image.

Creating a class template

//Creating a class template:// template_classfamily.h -- Name of the template file saved with .hextension

template <class T>

class myclass{ public:

myclass(){ };

T add(T a, T b)

{ return a + b;}

T multiply(T a, T b)

{

return a * b;

}

};

A class template is created with the identifier 'T'. The functions within the classcalled 'add' and 'multiply' are created in the public section of the class.

C++ program using a class template with a family of classes

#include <iostream.h>#include <stdlib.h>#include "template_classfamily.h"

class my_cl{ public: void showdata() { myclass<double> mcl3; //object of template class is declared doublez2=mcl3.add(51.49,38.51); //template class function //is referred cout<<"output from my_cl1 class.."<<z2<<endl; }};

class my_cl2{ public: void showdata() { myclass<double> mcl4; //object of template class is declared doublez2=mcl4.multiply(14,14); //template class function is //referred cout<<"output from my_cl2 class.."<<z2<<endl; }};

void main(){ my_cl m_cl; m_cl.showdata();

my_cl2 m_cl1; m_cl1.showdata();

myclass<int> mcl; //object of template class is declared //withint datatype int z=mcl.add(25,36); //template class function is referred cout<<"output from main() with int datatype.."<<z<<endl;

myclass<double> mcl1;//object of template class is declared //with double datatype double z1=mcl1.add(32.24,65.94); //template class function //is referred cout<<"output from main() with double datatype.."<<z1<<endl;

system("PAUSE");

}

A function 'add()' is being called from a family of classes declared within a C++program.

Output of a program using a function template with a family of classesThe four sets of outputs are shown, as the function 'add()' is being called four timesfrom the family of classes within a C++ program.

Copyright© 2002 DigitalThink, Inc. All Rights Reserved.

Work with templates

Template versatility

The class templates are used for creating generic classes, which can be referred from other classesin a C++ program. The template classes can also be passed as type arguments to other templates.This mechanism of passing one template class within another as a type argument is calledtemplate versatility in C++.

Click the View Image button to learn more about template versatility in C++.

Copyright© 2002 DigitalThink, Inc. All Rights Reserved.

Work with templates

Template specialization

The template describes a generic class, which can be referred with any valid data type. Specialization is amechanism in C++ through which a class can be declared using a specific data type. In the case of anormal template, there may be problems related to data type. For example, if you have created a classtemplate where the '>' symbol is used and you are referring that template class with char data type, thenyou might face a problem. To overcome these kinds of problems, a template specialization mechanism isused to restrict the accessibility of the template and to work with a specific data type. The entire templatespecialization is the combination of the following processes:

Implicit instantiation●

Explicit instantiation●

Explicit specialization●

Click the FlipBook button to learn about the processes involved in template specialization.

Transcript

Copyright© 2002 DigitalThink, Inc. All Rights Reserved.

The processes involved in template specialization

Click the following thumbnails to view the full-sized image.

Implicit instantiationImplicit instantiation is the simplest way of using a template. In thisprocess, the objects are declared with specific data type and thecompiler generates a specialized class definition for the programthat owns the object. The following statements should be written forimplicit instantiation:

For a variable:

My_array<int, 250> m_array;

For a pointer:

My_array<double, 32> *m_pt;m_pt = new My_array<int, 32>:

Explicit instantiationAt the time of declaring a template, the desired data type ismentioned in the case of explicit instantiation. So when you referthe class of that particular class template, you will find that the datatype is already defined. The following statement implements theconcept of explicit instantiation:

template my_array<char, 100>

In this case, the compiler generates a class definition withpre-defined data type char.

Explicit specialization:Explicit specialization is a definition of a type to be used instead ofthe general template. Sometimes it is required to modify a template,so that it can behave differently when instantiated for a particulartype. For example, you have defined a template for a classrepresenting a stored array for which items will be stored as theyare added to the array. If the template uses a '>' operator to comparevalues within the template, then it will work perfectly for numbersbut not for char data type. To convert the generic template into aspecialized template for char* type, you have to write the followingstatement:

template <> class stored_array<char *>

Copyright© 2002 DigitalThink, Inc. All Rights Reserved.

Work with templates

Module wrap-up

Templates are a mechanism supported by C++ for generating generic codes, which areindependent of data type. It enhances the code reusability feature of C++.

Now that you have completed this module you should be able to:

Describe how to use templates●

Describe function templates●

Describe class templates●

Use templates with a family of classes●

Describe template versatility and specialization●

Click the Quiz button to check your understanding of working with templates.

Copyright© 2002 DigitalThink, Inc. All Rights Reserved.

Getting acquainted with Standard Template Library

Module goals

Standard Template Library (STL) is a generic C++ library. This means that its components aremostly parameterized. Almost every component in STL is a template. This library is chieflycomposed of container classes , algorithms, and iterators.

Copyright© 2002 DigitalThink, Inc. All Rights Reserved.

Get acquainted with Standard Template Library

Standard Template Library

STL provides general-purpose utility classes that programmers can use in their applications. Youdo not have to worry about allocating and deallocating memory while using the classes availablein STL. These classes include array, list, stack , map and more.

STL provides some general algorithms for sorting, searching, and so forth. Besides these, STLalso provides some iterators and other options that you can apply on the above-mentioned classes.The generic algorithms of STL work on native C++ data structures such as strings and vectors.

Click the View Image button to learn about the advantages of STL.

Copyright © 2002 DigitalThink, Inc. All Rights Reserved.

Get acquainted with Standard Template Library

Basic elements of STL

Like many other class libraries, STL includes elements like container, algorithm, iterator, andallocator. The first three elements mentioned are the fundamental ones.

Click the MouseOver button to see a brief description of the elements of STL.

Transcript

Copyright© 2002 DigitalThink, Inc. All Rights Reserved.

Brief description of the elements of STL

Copyright© 2002 DigitalThink, Inc. All Rights Reserved.

Get acquainted with Standard Template Library

Containers

Containers are the base elements of STL. These are classes whose purpose is to contain otherobjects. Containers are data structures that store and manage a set of items. These items can be abasic data type such as int or char. Each of these classes is a template, and can be instantiated tocontain any type of object. Containers have constructors and destructors to provide allocation anddeallocation for stored items. The STL includes classes like vector , list , deque , set, multiset,map, multimap , hash set , hash multiset, hash map ,and hash multimap. All containers have thesame specification. To use the different types of containers, you require the appropriate headerfiles.

Click the FlipBook button to learn about the different types of containers.

Transcript

Click the FlipBook button to learn about the details of some containers.

Transcript

Copyright© 2002 DigitalThink, Inc. All Rights Reserved.

Different types of containers

Click the following thumbnails to view the full-sized image.

Types of containers

Sequence

Containerclasses

Description

Vector,list, deque

A sequence is a linear listthat stores all its elements ina linear order. These types ofcontainers support insertionor deletion at the beginningor at the end. They do notsupport insertion or deletionat a specific position.

Associative

Containerclasses

Description

Map,multimap,set

Variable sized containersthat support efficientretrieval of elements basedon keys. They store data inthe form of key and value. Akey has corresponding valueor values.

Container adaptors

Containerclasses

Description

Stack, queue,priority_queue

Restricted containersthat do not support allthe functionalitiesprovided by containers.

Copyright© 2002 DigitalThink, Inc. All Rights Reserved.

Details of some containers

Click the following thumbnails to view the full-sized image.

The vector containerA vector container is the simplest of all containers. It is a dynamic array whose sizecan vary as required. It allows the insertion and deletion of elements at the end. Itsupports random access and automatic memory management.

Some of the important functions of vectors include:

Function Description

back () Returns the last element

begin () Returns an iterator to the first element

front () Returns the first element

insert () Inserts an element into the vector

pop_back () Removes the last element

push_back () Adds an element to the end of the vector

Code for implementing vector

// vector.cpp

#include <iostream.h>#include <string.h>#include <vector.h>#include <stdlib.h> // header file for vector

const int NUM = 5;void main(){ vector<int> ratings(NUM); // define a vector container vector<string>titles(NUM); cout<<"Enter " << NUM <<" book ids and their ratings (0-10).\n\n"; int i;

for(i=0;i<NUM;i++) { cout<<"Enter title #"<<i + 1 << ":"; cin>> titles[i]; cout<<"Enter your rating (0-10): "; cin>> ratings[i]; cin.get(); } cout<<"\nThank you.You entered the following:\n\n" << "Book "<<"Rating \n"; for(i=0; i<NUM; i++) { cout<< titles[i] << " \t" << ratings[i] <<endl; } system("PAUSE");}

The above code shows how to use a vector container to store and access data.

Output of vector.cpp programThe above screenshot shows the output of vector.cpp program.

The deque containerThe deque container is similar to the vector container. It differs from a vector in that adeque container has two ends.This means that elements can be added or deleted fromboth front and back ends. The elements can be inserted at any specific location.

Some of the important functions of deque include:

Function Description

back () Returns the last element

begin () Returns an iterator to the first element

front () Returns the first element

insert () Inserts an element into the deque

pop_back () Removes the last element

pop_front () Removes the first element

push_back Adds an element to the end of the deque

push_front () Adds an element to the front of the deque

Code for implementing deque

//deque.cpp#include<iostream.h>#include<deque.h>#include<string>#include<stdlib.h>void main(){ deque<int> d1; // push_back adds items on the back of a deque d1.push_back(2); d1.push_back(4); d1.push_back(6); // push_front adds items in the front of the queue d1.push_front(8); d1.push_front(5); d1.push_front(3);

// Print all elements of deque using size() to find out the // size of deque cout<< "Contents of the queue: " ; for( int i=0; i< d1.size(); i++ ) { cout<< d1[i]<<endl; } cout<< "\n"; // See back and front functions to get last and first items // of the queue int output; output = d1.back() ; cout<< "Last Item of the queue: " << output ; cout<< "\n";output = d1.front() ; cout<< "First Item of the queue:" << output ; cout<< "\n" ; // Delete last item of the queue d1.pop_back(); // Delete first item of the queue d1.pop_front(); cout<< "Contents of the queue: \n" ; for( int i=0; i< d1.size(); i++ ) { cout<< d1[i]<< endl; } cout<< "\n" ; system("PAUSE");}

The above code shows how to use a deque container and its functions.

Output of deque.cppThe above screenshot shows the output of deque.cpp program.

The list containerA list supports traversal in both directions-from the beginning to the end and from theend to the beginning. Elements can be inserted or removed from anyposition-beginning, middle, or end. A list container is very useful when elements arefrequently added and removed from the middle of the container, and random accessof elements is not required.

Some of the important functions of list include:

Function Description

back () Returns the last element

begin () Returns an iterator to the first element

end() Returns an iterator to the end

front () Returns the first element

insert () Inserts an element into the list

pop_back () Removes the last element

pop_front () Removes the first element

push_back () Adds an element to the end of the list

push_front () Adds an element to the front of the list

remove () Removes elements from the list

sort () Sorts the list

The map and multimap containers

map<char, int> mp ;int i ;

for ( i=0; i<10; i++ ){ mp.insert( pair<char, int>('A'+i, 65+i ));}

Some of the important functions of map and multimap containers include:

Function Description

begin () Returns an iterator to the first element

count () Number of times an element occurs

end() Returns an iterator to the end

insert () Inserts elements

key_comp () Returns the function that compares keys

lower_bound () Returns an iterator positioned at the first locationwhere a pair with key could be inserted withoutviolating the ordering criteria. If no such location isfound, returns an iterator positioned at end().

Upper_bound () Returns an iterator positioned at the last locationwhere a pair with key could be inserted withoutviolating the ordering criteria. If no such location isfound, returns an iterator positioned at end().

The map and multimap containers store data in the form of a pair. Each pair has a keyand a value(s) corresponding to it; for example, pair myDetails = ( name<string>,age<int>). The data type of key might differ from the values.

Map containers allow only unique keys. A key can have some value but there cannotbe duplicate keys.

Multimap containers are similar to map except that they allow the storing of duplicatekeys. So, one key can have more than one value.

The set and multiset containersset<string> sdata;sdata.insert("Stephen");sdata.insert("Jane");sdata.insert("Harry");

Some of the important functions of set and multiset containers include:

Function Description

begin () Returns an iterator to the first element

count () Number of times an element occurs

end() Returns an iterator to the end

insert () Inserts elements

key_comp () Returns the function that compares keys

lower_bound () Returns an iterator positioned at the first locationwhere a pair with key could be inserted withoutviolating the ordering criteria. If no such location isfound, returns an iterator positioned at end().

Upper_bound () Returns an iterator positioned at the last locationwhere a pair with key could be inserted withoutviolating the ordering criteria. If no such location isfound, returns an iterator positioned at end().

Set containers are very similar to map containers except that the key portion is notseparated from the value portion. A set stores data in a form whereas a key is a part ofa value.

Set containers allow only unique keys, whereas in a multiset duplicate keys are alsosupported.

The queue container adaptor

queue<string> sdata;sdata.push("Stephen");sdata.push("Jane");sdata.push("Harry");

while ( !sdata.end() ){ cout<< sdata.front() <<" "; sdata.pop();}

Some of the important functions of queue container adaptors include:

Function Description

back () Returns the last element

empty () True if the queue is empty

front () Returns the first element

pop () Removes the first element

push () Removes the last element

size () Returns the number of elements in the queue

The queue is a first in first out (FIFO) queue. It has certain restrictions as comparedto other containers. Elements are inserted in a queue from the end and removed fromthe beginning. It is like a queue at an airport ticket counter. The first person in thequeue receives the ticket first. Push and pop are two major operations of the queue.

The stack container adaptor

stack<string> sdata;sdata.push("Stephen");sdata.push("Jane");sdata.push("Harry");

while ( !sdata.empty() ){ cout<< sdata.top() <<" "; sdata.pop();}

The stack is a last in first out (LIFO) queue. It is similar to a queue except thatelements are inserted from the top of the stack and also removed from the top of thestack. A stack can be compared to a stack of plates in the kitchen. Push and pop aretwo major operations of the stack.

Copyright© 2002 DigitalThink, Inc. All Rights Reserved.

Get acquainted with Standard Template Library

Algorithms

STL includes a large number of algorithms that manipulate the data stored in containers. Some ofthe basic algorithms are count, sort, search, and reverse.

Click the FlipBook button to learn about algorithms.

Transcript

Copyright© 2002 DigitalThink, Inc. All Rights Reserved.

Algorithms

Click the following thumbnails to view the full-sized image.

Algorithms and their descriptions

Algorithm Description

copy Copies a sequence

countReturns the number of elements in thesequence

equal Checks if two ranges are same

findSearches and returns the iterator to the firstoccurrence

lower_boundFinds the first point in the sequence that is lessthan a specified value

max Returns the maximum of two values

min Returns the minimum of two values

mismatchFinds the first mismatch between the twoelements in two sequences

remove Removes elements

reverse Reverses the order of a range

replace Replaces elements within a range

search Searches a subsequence within a sequence

sort Sorts a range

swap Exchanges two values, ranges

upper_bound Finds the last point in a sequence

merge Merges two sequences

The above table shows the algorithms that are most widely used to manipulate the data incontainers.

Implement algorithms to manipulate data in a lists

// algorithm.cpp#include<iostream.h>#include<list.h>#include<stdlib.h>

void main(){list<int> list1 ;int iCounter = 0 ;// You can add items to this list using push_front and push_back //members of thelist container// push_back adds items at the end of the list and push_front in //the front

list1.push_back(2);list1.push_back(7);list1.push_back(8);list1.push_back(5);list1.push_back(6);list1.push_back(1);

// Display all contentscout<<"========================== \n" ;cout<<" Original contents: \n" ;cout<<"========================== \n" ;list<int>::iterator p = list1.begin();while (p != list1.end() ){ cout<< *p++ << "\n";}

// Delete item from the list if item = 6cout<<"========================== \n" ;cout<<"Contents after deleting 6: \n" ;cout<<"========================== \n" ;list1.remove(6);

p = list1.begin();while (p != list1.end() ){cout<< *p++ << "\n";}

// Sort the listcout<<"========================== \n" ;cout<<"Contents after sorting: \n" ;cout<<"========================== \n" ;

// Call sort() function of list sorts the listlist1.sort();p = list1.begin();while (p != list1.end() )

{ cout<< *p++ << "\n";}system("PAUSE");}

The above code shows how to use different algorithms to act on the data stored incontainers.

Output of algorithm.cppThe above screenshot shows the output of algorithm.cpp program.

Copyright© 2002 DigitalThink, Inc. All Rights Reserved.

Get acquainted with Standard Template Library

Iterators

Containers do not offer access to their elements. Iterators are used to traverse the elements within acontainer. It means that iterators provide a mechanism to cycle through the contents of containers.Iterators are generalization of pointers. Iterators are mechanisms to decouple algorithms fromcontainers. Each type of container has predefined iterators. You can use these iterators when youuse a particular container. Iterators are very similar to smart pointers. They have increment anddereferencing operations.

Click the FlipBook button to learn about iterators.

Transcript

Copyright© 2002 DigitalThink, Inc. All Rights Reserved.

Iterators

Click the following thumbnails to view the full-sized image.

Iterators

Type Description

Random Access Stores and retrieves elements randomly

BidirectionalStores and retrieves elements forward andbackward (in both directions)

Forward Stores and retrieves elements forward only

Input Retrieves forward only

Output Stores forward only

The above table shows the five types of iterators.

Use of iterators to retrieve data

// iterator.cpp

#include <iostream.h>#include <map.h>#include <stdlib.h>

void main(){ map<char, int> mp ; int i ; for ( i=0; i<10; i++ ) { mp.insert( pair<char, int>('A'+i, 65+i )); } map<char, int>::iterator p; // declare iterator p= mp.begin();

while ( p!= mp.end() ) { cout<< p->first << " has ascii values of " << p->second <<endl; p++; } system ("PAUSE");}

The above code shows how to use iterators to retrieve data from a map container.

Output of iterator.cppThe above screenshot shows the output of iterator.cpp program.

Copyright© 2002 DigitalThink, Inc. All Rights Reserved.

Get acquainted with Standard Template Library

Function objects

A function object is an object that can be called using the normal function call syntax. STLincludes a large collection of function objects, also known as functors. Just as iterators aregeneralizations of pointers, function objects are generalizations of functions. The header filerequired for implementing function objects is functional.h.

STL includes many different predefined function objects:

Arithmetic operations - plus, minus, multiplies, divides, modulus, and negate●

Comparisons - equal_to, not_equal_to, greater, greater_equal, less, less_equal●

Logical operations - logical_and, logical_or, logical_not●

You can perform very sophisticated operations without actually writing a new function object,simply by combining predefined function objects and function object adaptors.

Click the MouseOver button to learn about the different types of function objects.

Transcript

Copyright© 2002 DigitalThink, Inc. All Rights Reserved.

Different types of function objects

Copyright© 2002 DigitalThink, Inc. All Rights Reserved.

Get acquainted with Standard Template Library

Additional components of STL

Additional components of STL include adaptors and allocators.

Adaptors

Adaptors modify the interface of other components. The different types of adaptors are:

Function adaptors: negators, binders●

Container adaptors: stack, queue, priority queue●

Iterator adaptors: reverse iterators, insert iterators●

Click the FlipBook button to learn about the different types of adaptors in STL.

Allocator

Allocators are responsible for memory management in STL. Allocators allocate and deallocatememory automatically for a container. STL provides a default allocator called Allocator. You canalso create your own custom allocators. You can take advantage of allocators to write customizedcontainer code.

Copyright© 2002 DigitalThink, Inc. All Rights Reserved.

Transcript

Different types of adaptors in STL

Click the following thumbnails to view the full-sized image.

Function adaptorsFunction adaptors are template classesthat provide an existing class with anew interface. They can be applied oncontainers or iterators.

The header function.h defines functionadaptors.

Container adaptorsContainer adaptors are used to createnew containers from existingcontainers. This means that theseadaptors extend the functionality of anexisting container and addfunctionality to a new container.

STL provides three container adaptors:

Stack●

Queue●

Priority queue●

StackThe stack is a container adapter thatgives the functionality of a stack,especially like the FILO (first-in,last-out) data structure.

Some of the important functions ofstack include:

Function Description

empty ()True if the stack isempty

pop ()Removes the topelement

push ()Adds an element tothe top

size (0)Returns the numberof elements in thestack

top ()Returns the topelement of the stack

QueueQueue is a container adapter that givesthe functionality of a queue-especiallya FIFO (first-in, first-out) datastructure.

Some of the important functions ofqueue include:

Function Description

empty ()True if the queue isempty

pop ()Removes the topelement

push ()Adds an element tothe top

size (0)Returns the numberof elements in thequeue

top ()Returns the topelement of the queue

Priority queuePriority queues are like queues, but theelements inside the data structure areordered by some predicate.

Some of the important functions ofpriority queue include:

Function Description

empty ()True if the priorityqueue is empty

pop ()Removes the firstelement

push () Adds an element

size (0)Returns the numberof elements in thepriority queue

top ()Returns the value ofthe element withhighest priority

Copyright© 2002 DigitalThink, Inc. All Rights Reserved.

Get acquainted with Standard Template Library

Module wrap-up

The Standard Template Library offers a number of useful containers. STL is easily extensible byadding algorithms, and once you have enough experience with STL, you can even add containers.Containers are implemented with generic data structures.

Now that you have completed this module you should be able to:

Define Standard Template Library●

Identify basic elements of STL●

Describe containers and algorithms●

Describe iterators●

Describe function objects●

Identify additional components of STL●

Some or all of these terms may be new to you:

container classes●

algorithms●

iterators●

array●

stack●

map●

vector●

list●

deque●

set●

multiset●

multimap●

hash_set●

hash_multiset●

hash_map●

hash_multimap●

function object adaptors●

Click the Quiz button to check your to check your understanding of STL.

Copyright© 2002 DigitalThink, Inc. All Rights Reserved.

Run-time type information and type casting

Module goals

Run-time type information (RTTI) can be considered an extension to static type information. Itoffers the user information about pointers and references. This information is similar to the typeinformation that a compiler maintains when compiling a C++ program. RTTI can perform twotypes of activities--getting type information from run-time elements like pointers and references,and getting type information from static elements like classes.

Copyright© 2002 DigitalThink, Inc. All Rights Reserved.

Run-time type information and type casting

The role of RTTI

Polymorphism allows you to call a derived class function with a base class pointer. One problemthat may arise when you are using polymorphism is that you do not know exactly what kind ofobject is being pointed to. Look at this simple example of polymorphism.

The above image is an example of a class hierarchy that uses polymorphism. The generic type isthe base class shape, while the specified types are the derived classes--circle, square, and triangle.In this example, the virtual function in the shape class is draw(). The function draw() is redefinedin all the derived classes as the draw(), and in the base class is a virtual function. You can call thedraw() function in the derived classes using the base class pointer. The proper behavior will occureven though draw() is called through a generic shape pointer.Thus you create a specific object (circle, square, or triangle), by taking its address and casting it toa Shape* (forgetting the specific type of the object), and then you use that anonymous pointer inthe rest of the program.

RTTISuppose you have a programming problem that can be solved easily if you know the exact type ofbase pointer. For example, you want to allow your users to highlight the shapes of a particulartype by turning them green. Your first approach will be to try a virtual function like TurnColor(),which allows enumerated arguments of color and of shape::circle, shape::square, orshape::triangle.To solve such problems, most class library designers set virtual functions in the base class toreturn type information about the specific object at run-time. You may have come across librarymember functions like isA() and typeOf(). These are vendor-defined RTTI functions. When

exception handling was added to C++, the implementation required some run-time typeinformation to be added into the virtual function tables. With a small extension in language, theprogrammer could also get the run-time type information about an object. RTTI, like exceptions,depends on type information residing in the virtual function table.

Click here to learn more.

If you try to use RTTI on a class that has no virtual functions, you'll getunexpected results.

Copyright© 2002 DigitalThink, Inc. All Rights Reserved.

Run-time type information and type casting

Dynamic cast operators

C++ has three components supporting RTTI:

The dynamic_cast operator generates a pointer to a derived type from a pointer to a basetype, if possible. Otherwise, the operator returns 0, the NULL pointer.

The typeid operator returns a value identifying the exact type of an object.●

A type_info structure holds information about a particular type.●

Click the FlipBook button to learn about the dynamic_cast operator.

Transcript

Copyright© 2002 DigitalThink, Inc. All Rights Reserved.

Dynamic_cast operator

Click the following thumbnails to view the full-sized image.

Role of the dynamic_cast operatorThe dynamic_cast operator is supposed to be the most widely used RTTIcomponent. It does not answer the question of what type of object a pointerpoints. Instead, it states whether you can safely assign the address of the objectto a pointer of a particular type.

Criteria for a type safe cast

class Employee{// has virtual methods};class Laborer : public Employee{....};class Manager : public Laborer{....};

// Suppose you have the following pointers:Employee* pe = new Employee;Employee* pl = new Laborer;Employee* pm = new Manager;

// Consider the following type casts:Manager* p1 = (Manager*)pm; //#1Manager* p2 = (Manager*)pe; //#2Laborer* p3 = (Manager*)pm; //#3

The type casts that are guaranteed to be safe are the ones in which:

The pointer is the same type as the object●

The pointer is a direct or indirect base type for the object●

#1 is safe, because it sets a type Manager pointer to point to a type Managerobject.#2 is not safe, because it assigns the address of a base object Employee to aderived class (Manager) pointer.#3 is safe, because it assigns the address of a derived object to a base classpointer. The public derivation promises that a Manager object is also a Laborerobject (direct base) and an Employee object (indirect base).

Dynamic_cast syntaxDynamic_cast<Type *>(pt)

For example:

Laborer pm = dynamic_cast<Laborer *> (pe);This general expression converts the pointer pt to a pointer of type Type * if thepointed-to object (*pt) is of type Type or derived directly or indirectly from typeType. Otherwise, the expression evaluates to 0 or NULL.

Copyright© 2002 DigitalThink, Inc. All Rights Reserved.

Run-time type information and type casting

Typeid operators and type_info structures

The typeid operator determines if two objects are of the same type. It accepts two arguments:

The name of the class●

An expression that evaluates to an object●

This operator returns a reference to a type_info object. type_info is a class, which is defined in thetypeinfo header file. The type_info class overloads the == and != operators. You can use theseoperators to compare types.

For example, the expression:

typeid (Manager) == typeid( *pe )

returns a boolean value true, if pe points to a Manager object; otherwise it returns false. If pe is aNULL pointer, the program throws a bad_typeid exception. This exception type is derived fromthe exception class and is declared in the typeinfo header file.The implementation of the type_infoclass varies from vendor to vendor. However, in all cases it includes a name() member that returnsa string that is typically the name of the class.

Click the MouseOver button to learn about the typeid operators and type_infostructures.

Transcript

Copyright© 2002 DigitalThink, Inc. All Rights Reserved.

Typeid operators and type_info structures

Copyright© 2002 DigitalThink, Inc. All Rights Reserved.

Run-time type information and type casting

Implementation of RTTI

You are aware of the facilities provided by RTTI. So now it's time to implement this mechanism.

Click the View Image button to see the implementation of RTTI.

Copyright© 2002 DigitalThink, Inc. All Rights Reserved.

Run-time type information and type casting

Type casting

The C++ standard is full of powerful additions to the language: templates, run-time typeidentification (RTTI), namespaces, and exceptions--to name a few. Now you will learn about oneof the minor extensions--the C++ casting operators.

The C++ casting operators are intended to provide a solution to the shortcomings of the oldC-style casts by providing:

Improved syntax: Casts have a clear, concise, although somewhat unwieldly syntax. Thismakes casts easier to find, understand, and maintain.

Improved semantics: The intended meaning of a cast is no longer ambiguous. It is possiblefor compilers to detect improper casting operations knowing what operation theprogrammer wanted the cast to perform.

Type-safe conversions: Allow some casts to be performed safely at run-time. This enablesprogrammers to check whether a particular cast is successful or not.

The four types of type cast operators that provide more discipline to the casting process are asfollows:

static_cast●

const_cast●

reinterpret_cast●

dynamic_cast●

Click the FlipBook button to learn about the different types of type cast operators.

Transcript

Copyright© 2002 DigitalThink, Inc. All Rights Reserved.

Different types of type cast operators

Click the following thumbnails to view the full-sized image.

The static_cast operatorstatic_cast <type-name> (expression)Subject to certain restrictions, you can use static_cast to:

Convert a base class pointer to a derived class pointer●

Perform arithmetic conversions●

Convert an int to an enum●

Convert a reference of type X& to another reference of type Y&●

Convert an object of type X to an object of type Y●

Convert a pointer-to-member to another pointer-to-member within thesame class hierarchy

The const_cast operatorconst_cast<type-name>(expression)The const_cast operator is used to remove the const attribute from a class. Apointer to any object type is explicitly converted to a type that is identical exceptfor the const qualifier. The result of this conversion will refer to the originalobject.

The reinterpret_cast operatorreinterpret_cast<type-name>(expression)The reinterpret_cast operator can be used for conversions such as char* to int*,or any_class* to a completely_different_class*. These conversions, however, areextremely unsafe. The safest use for the result of a reinterpret_cast is to cast itback to its original type.

The dynamic_cast operatordynamic_cast< type-name >(v)This cast is used with classes having virtual functions. type-name must be apointer or reference to a class type and v must be a corresponding pointer valueor reference value.

Copyright© 2002 DigitalThink, Inc. All Rights Reserved.

Run-time type information and type casting

Module wrap-up

RTTI can be thought of as a secondary feature in C++ that is used to overcome complexsituations. Normally programmers intentionally ignore the exact type of an object and let thevirtual function mechanism implement the correct behavior for that type. Occasionally it is usefulto know the exact type of an object for which you only have a base pointer. Often this informationallows you to perform a special-case operation more efficiently or prevent a base-class interfacefrom becoming ungainly.

Now that you have completed this module you can:

Define RTTI●

Describe dynamic cast operators●

Describe typeid operators and typeid_info structures●

Implement RTTI●

Describe type cast operators●

Some or all of these terms may be new to you:

Virtual function table●

Click the Quiz button to check your understanding of RTTI.

Copyright© 2002 DigitalThink, Inc. All Rights Reserved.

Course Project

Module goals

You are only one step away from completing this course. To better prepare you to be an efficientC++ programmer, we have designed a few programs in which you will put into practice some ofwhat you've learned.

In this module, you will complete a series of exercises in which you respond to different real lifeproblems that occur frequently. You will provide solution to these problems using the C++programming language.

Copyright© 2002 DigitalThink, Inc. All Rights Reserved.

Course Project

Scenario

The software companyYou work in a reputed software organization as a senior C++ programmer. You provide solutionsto different problems forwarded to you by your clients. You analyze their problems, constructlogical solutions, and implement the solutions in C++.

Your roleTo provide effective solution as per the client's requirement

After completing the three exercises in this module, you will have demonstrated your ability to:

Add a node to a doubly linked list●

Traverse a linked list●

Delete a node from a linked list●

Insert data into a file through streams●

Fetch data from a file through streams●

Create a class template●

Use the template with family of classes●

Copyright© 2002 DigitalThink, Inc. All Rights Reserved.

Course Project

Implement doubly linked list

Scenario

Click Exercise to check your understanding of implementing doubly linked list.

Click here to learn more.

Copyright© 2002 DigitalThink, Inc. All Rights Reserved.

Course Project

File I/O through streams

Scenario

Click Exercise to check your understanding of File I/O through streams.

Copyright© 2002 DigitalThink, Inc. All Rights Reserved.

Course Project

Create a class template and use the same with family of classes

Scenario

Click Exercise to check your understanding of creating class templates for usingthe same with family of classes.

Copyright© 2002 DigitalThink, Inc. All Rights Reserved.

Course conclusion

Copyright© 2002 DigitalThink, Inc. All Rights Reserved.

Course conclusion

Course conclusion

Congratulations! You have completed the third course in the series.

Learning objectives

Having completed this course, you should now be able to:

Exception handling●

Templates and Collections●

Input and output in C++ programs●

Run time type identification●

Copyright© 2002 DigitalThink, Inc. All Rights Reserved.

Course conclusion

We'd love your feedback

Please take a couple of minutes to complete the simple course evaluation on the next page. This isyour chance to let us know how you think we can improve our courses--we'll really use yourinput! Additionally, completing the survey signifies you have finished the course and may be arequirement for students with a company account. By submitting the survey, you complete acrucial step in the process of earning continuing education credit and qualifying for a certificate inthis course.

Your comments appreciated

If you have any comments about your Web-based training experience in general, you can alsosend us your feedback via email.

Copyright© 2002 DigitalThink, Inc. All Rights Reserved.

Algorithms

A series of steps that systematically outline how to accomplish a goal. Array

An ordered and indexable sequence of values. C++ supports arrays of a single dimension or of multiple dimensions.

Buffer Block of memory used as a temporary storage unit of bytes while transferring bytes from device to program or vice versa.

Bytes Binary representation of character or numeric data. For text oriented program a character is represented as a byte.

Container A container is an object that stores other objects (its elements), and that has methods for accessing its elements.

Container classes Container classes are types of class or template used to hold objects of other types. Lists and stacks would be examples of container classes.

Deque A deque container is similar to the vector container except that elements can be added or deleted from both--front and back ends. Elements can also be inserted at any specific position.

Function object adaptors These are template classes that provide an existing class with a new interface. Hash_map Hash_map is a Hashed Associative Container that associates objects of type Key with objects of type Data. Hash_multimap Hash_multimap containers are similar to hash_map containers except that they allow storing duplicate keys. (You can find the explanation of hash_map containers in the glossary.) Hash_multiset Hash_multiset containers are similar to hash_set containers except that they allow storing duplicate keys. Hash_set Hash_set is a Hashed Associative container that stores objects of type Key. It is useful in applications where it is important to be able to search for an element quickly. . (You can find the explanation of hash_map containers in the glossary.) Hashed Associative Container A Hashed Associative Container is an Associative Container whose implementation is a hash table. The elements of a Hashed Associative Container are not guaranteed to be in any meaningful order; in particular, they are not sorted. Head Head is the first item of a list. Iterators Iterators are a generalization of pointers: they are objects that point to other objects. As the name suggests, iterators are often used to iterate over a range of objects: if an iterator points to one element in a range, then it is possible to increment it so that it points to the next element. Copyright© 2002 DigitalThink, Inc. All Rights Reserved.

Glossary

List A collection of items accessible one after another beginning at the head and ending at the tail. Map A map is a data structure that stores pairs of keys and values. A value may be inserted or retrieved based on its key. In C++, map is a container class in the Standard Template Library, STL. Multimap Multimap containers are similar to map containers except that they allow storing duplicate keys. Multiset Multiset containers are similar to set containers except that they allow storing duplicate keys. Node The record in a linked list is called a node Set Set is a container that stores objects of type Key. It is similar to map containers except that the key part is not separated from the value part. Stack A stack is a LIFO (Last in first out) queue. The elements that are inserted from the top of the stack are removed from the top of the stack too. Streams Streams are flows of data used by C++ programs to read from and write into the disk from a program and vice versa. Tail Tail is the last item of a list. Toggle breakpoint This is a tool supported by bloodshed compiler to mark a particular statement as the starting point for debugging. Vector Vector container is the simplest container. It supports random access and provides insertion and deletion of elements at the end. Virtual function table A lookup table used for dispatching virtual function calls. A class object for a class containing virtual functions will contain a pointer to a virtual table.

Copyright© 2002 DigitalThink, Inc. All Rights Reserved.

Glossary