0% found this document useful (0 votes)
2 views

ch01

Chapter 1 introduces data structures, including vectors, lists, maps, and trees, and discusses abstract data types (ADTs) using C++ classes. It covers the implementation and usage of classes and objects, emphasizing encapsulation, member functions, and data abstraction. The chapter also explains constructors, destructors, and the organization of class definitions, including public and private access specifiers.

Uploaded by

Ping
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

ch01

Chapter 1 introduces data structures, including vectors, lists, maps, and trees, and discusses abstract data types (ADTs) using C++ classes. It covers the implementation and usage of classes and objects, emphasizing encapsulation, member functions, and data abstraction. The chapter also explains constructors, destructors, and the organization of class definitions, including public and private access specifiers.

Uploaded by

Ping
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 46

Chapter 1

Introduction to Data Structures

1
Outline

• Overview of Data Structures


 Vectors, Lists, Maps, and Trees
• Abstract Data Type (ADT)
 Data Abstraction with struct Data Type
• C++ Classes and Objects
 Class Declaration
• Data Member (Fields) and Member Functions (Methods)
• Encapsulation and Information Hiding
 Class Implementation
 Declaring and Using Objects
 Inline Implementation of a Class
• Application Programming Interface (API)
 Example: Random Numbers
• string class

2
Storage Containers (Vectors)

Containers such as vectors, lists or maps (or trees) are


storage structures that provide ways to access data and
insert/delete items.

• A vector has all of the nice indexing features of an array along


with the ability to dynamically grow to meet demand.

// output elements of v
for(i = 0; i < v.size(); i++)
cout << v[i] << " "

Output: 7 4 9 3 1

3
Storage Containers (Vectors)

• A vector is a "super-array“, meaning all familiar array


algorithms work.
• You also have the freedom to to grow or shrink it.

vecto r v (w ith 5 elem en ts)


7 4 9 3 1
v.resize (8 ); (gro w to 8 elem en ts)
7 4 9 3 1 0 0 0
v.resize (3 ); (sh rin k to 3 elem en ts)
7 4 9

4
Storage Containers (Vectors)

• Vectors allow for direct access to their elements through an


index, but are not efficient storage structures for:
 insertion of items at arbitrary positions in a list.
 deletion of items at arbitrary positions in a list.

V ecto r 15 20 30 35 40 V ecto r 1 5 2 0 3 0 3 5 4 0
In sert 2 5 at 25 E rase 2 0 at
15 30 35 40
P o sitio n 2 1 5 2 0 30 35 40
P o sitio n 1
S h ift righ t 2 0 S h ift left

5
Storage Containers (Lists )

• list container
 each element has a reference that identifies the next item in

the list.
 Adding a new item involves breaking a link in the chain

and creating two new links to connect the item.

//

fro n t re a r
n e w Ite m

6
Storage Containers (Maps)

Airlines and telecommunication companies use a grid of


nodes and interconnecting edges to represent cities and
routers in a network.

D en ver
752 604

648 A lb u q u erq u e
S an F ran cisco 763
432
504
P h o en ix
S an D iego 355

7
Storage Containers (Trees )
 A tree is a container that stores elements as nodes emanating
from a root.
 The tree holds 8 airbill numbers. Any search requires at most 3
movements along a path from the root.

R oot
G 9B 7
B 40A
N T2 P

F A 27
H 14K W 29Z

D 29Z
TV 9 3

8
Data Abstraction with struct Data Type

• struct, an abbreviation for structure, is a C / C++ reserved keyword

• Data Abstraction
 to group together related variables (or a record) using one entity
 The Data Type of the variables can be (and usually are) different

• Syntax
struct Structure_Name
{
Data_Type data_member_1;
Data_Type data_member_2;

Data_Type data_member_n;
};
Don’t forget this semicolon !!!

9
Example 1

• Student’s name, age, grade should be grouped as belonging to


the student.
• Define the (abstract) structure (type) Student:
struct Student
{
string name;
int age;
char grade;
};
• Declare a concrete variable (object, instance) student1:
Student student1;
• Use:
student1.name = “Tom Superman”;
dot (member selection) operator to access member variable
10
Example 2

• Employee’s name, social security number, and pay rate.


• Define the (abstract) structure (type) Employee:
struct Employee
{
string name;
string ssn;
double payRate;
};
• Declare a concrete variable (object, instance) emp:
Employee emp;
• Use:
cin >> emp.name;
cin >> emp.payRate;
emp.payRate = emp.payRate + 2.0;
11
Example 2 – complete code
// empstruct.cpp
#include <iostream>
using namespace std;
struct Employee
{
string name;
string ssn;
double payRate;
};
int main()
{
Employee emp;
cout << “Input name: “;
cin >> emp.name;
cout << “Input pay rate: “;
cin >> emp.payRate;
emp.payRate = emp.payRate + 2.0;
cout << “New pay rate is: “ << emp.payRate;
return 0;
} 12
How about 2 students and 20 employees?

• Declare:
Student student1, student2;
Employee emp[20];
• Use:
cin >> student1.name;
cin >> student2.name;
for(int i=0; i<20; i++)
{
cin >> emp[i].name;
cin >> emp[i].ssn;
emp[i].payRate = 12.5;
}
1. Without struct, we have to use two arrays
2. struct can do something more in C++ (we will get to this later)

13
Classes and Objects

• A class is a collection of (data) member variables combined


with a set of related member functions that operate on these
variables.
• A class encapsulates data (variables) and the operations
(functions) on them into a single entity, which improves
program modularity, i.e., make it easier to understand and
modify.
• A class produces programs for the user (either end-user or
other programmers),
 separating what from how (implementation details)
 allowing access to part but securing (hiding) other parts

14
Classes and Objects

• An object is a variable whose type is a class.

• An object is an instance of its class.

• An object has the data members of its class and can call the
member functions of its class

• Class defines an abstract data type (ADT) while object is the


concrete example.

15
Syntax of classes

• class ClassName
{
public: Don’t forget this colon !!!
member functions
member variables (rarely)

private:
member variables
member functions declarations (internal use only)
}; Don’t forget this semicolon !!!

• Note that class, private, and public are C++ reserved words.

16
Example 1 – Student class

// student.cpp int main()


#include <iostream> {
using namespace std; Student stu;

class Student stu.setName(“Tom Superman”);


{
public: cout << “The name is: “
void setName(string inName) << stu.getName();
{ name = inName; }
return 0;
string getName() }
{ return name; }

private:
string name;
};
17
Classes (Private/Public Sections)

• The public and private sections in a class declaration allow


program statements outside the class different access to the
class members.

pr i vate :
data m e m be rs
a c c e ssible to the
im ple m e nta tion of
m e m be r func tio ns
the m e m be r func tions publ i c :
ac c e s s ible by
data m e m be rs any pro gram s tate m e nt
m e m be r func tio ns

18
Classes (Private/Public Sections)

• Public members of a class are the interface of the object to the


program.
 Any statement in a program block that declares an object can access a
public member of the object

a c c e ssible to the
im ple m e nta tion of
the m e m be r func tions publ i c :
ac c e s s ible by
data m e m be rs any pro gram s tate m e nt
m e m be r func tio ns

19
Classes (Private/Public Sections)

• The private section typically contains the data values of the


object and utility functions that support class implementation.
 Only member functions of the class may access elements in the private
section.

pr i vate :
data m e m be rs
a c c e s s ible to the
im ple m e nta tion of
m e m be r func tio ns
the m e m be r func tions

20
Example 2 – MyData class

#include <iostream> int main()


using namespace std; {
class MyData MyData obj;
{ obj.enterData(200);
public: obj.showData();
void enterData(int d) return 0;
{data = d;}
}
void showData()
{cout << data;}

private:
int data;
};

21
Example 3 – Employee class

// employee.cpp int main()


{
#include <iostream> Employee emp;
#include <string> string sName;
using namespace std; double dPayRate;
class Employee
{ cout << “Input name:
public: “;
cin >> sName;
void setName(string inName)
cout << “Input pay
{ name = inName; } rate: “;
cin >> dPayRate;
void setPayRate(double inPR)
{ payRate = inPR; } emp.setName(sName);
emp.setPayRate(dPayRate);
private:
string name; return 0;
string ssn; }
double payRate;
};
22
Example 4 – string class

• greeting is an object (instance) of class string


• length() is a member function of class string
• greeting.length() calls the method length() of object
greeting and returns the length
• Suppose class string has a field int theLength;
the implementation (which we don’t know) of length( ) might be
int length( )
{
return theLength;
}
• We are NOT allowed use greeting.theLength to access the field
theLength, but have to call the method length()
23
Definitions

• Member variables can be any data types or data


structures, e.g. int, double, string, char, array, struct,
even another class.

• Member functions belong to several categories:


 constructors, which create objects of the class
 accessors, which return values of attributes
 modifiers, which modify the values of attributes

24
constructors and destructors

• A constructor is a special member function that initializes its data members


 It MUST has the name of the class
 It has NO return value and we do NOT use keyword void either.
 It may or may not have a parameter list. The constructor will be automatically
called during the creation (declaration) of a class object and uses the values in
the argument list to initialize the data members

• C++ automatically provides a default constructor if you don’t define one.


 It will be silently removed once you define a custom constructor. You have to
explicitly redefine it.

• A destructor cleans up after your object and free any memory you might
have allocated.
 a destructor has no return value and no parameters and MUST be named
~ClassName
 destructor is optional

25
constructors and destructors

class Example
{ int main()
public: {
// create an object and set data to 0
Example(){data=0;} Example obj1;
obj1.showData();
//constructor with parameter
Example(int x) {data = x;} obj1.enterData(100);
obj1.showData();
void enterData(int d)
{data = d;}
// create an object and set data to 200
void showData() Example obj2(200);
{cout << data << endl;} obj2.showData();

//destructor return 0;
~Example(){} }
Output:
private:
int data; 0
}; 100
200
26
accessors and modifiers – class definition

#include <iostream> // Sample Class


using namespace std;

class Rectangle // define a class named rectangle


{
public:
void setData(double, double); //modifier function
double getWidth() {return width;} //inline accessor function
double getLength() {return length;} //inline accessor function
double getArea() {return area;} //inline accessor function
private:
void calcArea() {area = width * length;} //inline modifier function
double width;
double length;
double area;
};
NOTE the double colon!!!
void Rectangle::setData(double w, double l) //definition of setData
{
width = w;
length = l;
calcArea(); // call the private member function calcArea
}
27
Scope resolution Operator

• The symbol :: (double colon) signals the compiler that the


function is a member of the class.
 The statements in the function body may access all of the public and
private members of the class.

• The :: operator allows you to code a member function like any


other free function.

returnType className::functionName(argument list)


{
<C++ statements>
}

28
accessors and modifiers – instantiation and usage

int main()
{
Rectangle box; //instantiation of the class rectangle
double wide, high;
cout<<”Enter the length of the rectangle\n”;
cin >> wide;
cout << ”Enter the width of the rectangle\n”;
cin >> high;

box.setData(wide, high);
cout << ”Width: “ << box.getWidth() << endl;
cout << ”Length: “ << box.getLength() << endl;
cout << ”Area: “ << box.getArea() << endl;
return 0;
}

29
const accessor Functions

• Text page 12 - 13

• To insure that accessor functions do not make changes to any variables,


we can specify const

return_type function_name (parameter list) const;

Example:
double getWidth() const;

30
Using Header Files – Approach I

• So far, the definition of a class is in the same file as the main


program, i.e., the program that uses the class
• We have used header files such as iostream, fstream, iomanip,
string, and cmath
 These header files contain methods (functions) that can be used in our
programs.
• We can write the header into one file (with a file extension
of .h). This file will contain both the declaration and
implementation of (the methods of) the class.
 The #include preprocessor command will then add the functions to
our program
 When we compile our program, the header file is also compiled with
our program
31
Header file contains class definition

// This is rectangle.h header file


#include <iostream> // Sample Class
using namespace std;
class Rectangle //define a class named rectangle
{
public:
void setData(double, double); //modifier function
double getWidth() {return width;} //inline accessor function
double getLength() {return length;} //inline accessor function
double getArea() {return area;} //inline accessor function
private:
void calcArea() {area = width * length;} //inline modifier function
double width;
double length;
double area;
};
void Rectangle::setData(double w, double l) //definition of setData
{
width = w;
length = l;
calcArea(); //call the private function calcArea
}
32
main program instantiates and use the class

// testrectangle.cpp contains main function


#include “rectangle.h”

int main()
{
Rectangle box; //instantiation of the class rectangle
double wide, high;
cout<<”Enter the length of the rectangle\n”;
cin >> wide;
cout << ”Enter the width of the rectangle\n”;
cin >> high;

box.setData(wide, high);
cout << ”Width: “ << box.getWidth() << endl;
cout << ”Length: “<< box.getLength() << endl;
cout << ”Area: “<< box.getArea() << endl;
return 0;
}

33
Using Header Files – Approach II

• We can also write the declaration and implementation in two


separate files
– The header file contains the declaration of the class to be used (with a
file extension of .h).

– Then the implementation of (the methods of) a class are written in


separate file (with file extension of .cpp) called the implementation
(source) file.

– The include preprocessor command will not add the implementation to


your program. Instead it will make a reference to the functions.
– This saves time since the implementation file does not need to be compiled
on each usage.

34
Header file

• File extension is .h
could use any symbol that has not been defined

#ifndef file_name
#define file_name

class declarations
...
#endif

• The #ifndef...#endif asks if the file_name (symbol) has been


defined already by another include.
• If it has, the header file has already preprocessed the current inclusion and
jumps to #endif
• To protect against multiple inclusions
35
Example: Rectangle class
// Contents of rectangle.h

#ifndef rectangle_h
#define rectangle_h

class Rectangle
{
public:
void setData(double, double);
double getWidth() {return width;}
double getLength() {return
length;} double getArea() {return
area;}
private:
double width;
double length;
double area;
void calcArea() {area = width *
length;}
};
36
#endif
Implementation (Source) File

• File extension is .cpp

#include “file_name”

class implementation including


methods definitions,
initialization of static variables,
etc.

• file_name is the header file, i.e., the .h file, which is in quotes “ ”


instead of <...>

• The quotes tells the compiler to look for the header file in the file folder of
the program instead of the file folder containing the standard header files
like iostream

37
Example: Rectangle class

// Contents of rectangle.cpp

#include “rectangle.h”

void Rectangle::setData(double w, double l)


{
width=w;
length=l;
calcArea();
}

38
Without inline implementations
// rectangle.h header file without inline implementation
#ifndef rectangle_h
#define rectangle_h

class Rectangle
{
public:
void setData(double, double);
double getWidth();
double getLength();
double getArea();
private:
double width;
double length;
double area;
void calcArea();
};

#endif
39
Without inline implementations
// rectangle.cpp implementation file
#include “rectangle.h”

void Rectangle::setData(double w, double l)


{
width=w;
length=l;
calcArea();
}
double Rectangle::getWidth()
{ return width; }
double Rectangle::getLength()
{ return length; }
double Rectangle::getArea()
{ return area; }
void Rectangle::calcArea()
{ area = width * length; } 40
The test program of Rectangle class

// testRectangle.cpp contains main function

#include “rectangle.h”

int main ()
{
Rectangle rect;
rect.setData(5, 10);
cout << rect.getArea();

return 0;
}

41
API (randomNumber Class)

class randomNumber Member functions “d_random.h”

double frandom();
Return a real number x, 0.0 <= x < 1.0

int random();
Return a 32-bit random integer m, 0 <= m < 231-1

int random(int n);


Return a random integer m, 0 <= m < n

42
Generating Random Numbers

The loop generates 5 integer random numbers in the range 0 to


40 and 5 real random numbers in the range 0 to 1.

int item, i;
double x;

for (i = 0; i < 5; i++)


{
item = rndA.random(40); // 0 <= item < 40
x = rndB.frandom(); // 0.0 <= x < 1.0
cout << item << " " << x;
}

43
String Functions and Operations

int find_first_of(char c, int start = 0):


Look for the first occurrence of c in the string beginning at index start.
start
Return the index of the match if it occurs; otherwise return -1.
By default, start is 0 and the function searches the entire string.

int find_last_of(char c):


Look for the last occurrence of c in the string. Return the index of the
match if it occurs; otherwise return -1.
Since the search seeks a match in the tail of the string, no starting
index is provided.

44
String Functions and Operations

string substr(int start = 0, int count = -1):


Copy count characters from the string beginning at index start and
return the characters as a substring. If the tail of the string has fewer
than count characters or count is -1, the copy stops at end-of-string.

By default, start is 0 and the function copies characters from the


beginning of the string. Also by default, the function copies the tail of
the string.

int find(const string& s, int start = 0):


The search takes string s and index start and looks for a match of s
as a substring. Return the index of the match if it occurs; otherwise
return -1.
By default, start is 0 and the function searches the entire string.

45
String Functions and Operations

void insert(int start, const string& s):


Place the substring s into the string beginning at index start.
start
The insertion expands the size of the original string.

void erase(int start = 0, int count = -1):


Delete count characters from the string beginning at index start.
start If
fewer than count characters exist or count is -1, delete up to end-of-
string.
By default, start is 0 and the function removes characters from the
beginning of the string.
Also by default, the function removes the tail of the string.
Note that no arguments at all truncates the string to the empty string
with length 0
46

You might also like