container classes general vectors lists maps adt review classes - declaration

38
1 Container Classes Container Classes General Vectors Lists Maps ADT Review ADT Review Classes Classes -Declaration -Private/Public Sections Example time24 function addTime time24 function addTime () () Lecture 1 Lecture 1 Introduction: C++, Data Structures Introduction: C++, Data Structures Scope Resolution Scope Resolution Operator Operator Rectangle Class Example Rectangle Class Example APIs and Example APIs and Example -Constructor -Operations -RandomNumber Class Generating Random Generating Random Numbers Numbers String Functions and String Functions and Operations Operations

Upload: charles-donovan

Post on 30-Dec-2015

27 views

Category:

Documents


0 download

DESCRIPTION

Lecture 1 – Introduction: C++, Data Structures. Container Classes General Vectors Lists Maps ADT Review Classes - Declaration -Private/Public Sections Example time24 function addTime (). Scope Resolution Operator Rectangle Class Example APIs and Example - Constructor - PowerPoint PPT Presentation

TRANSCRIPT

1

Container ClassesContainer Classes GeneralVectorsListsMaps

ADT ReviewADT Review

ClassesClasses-Declaration-Private/Public Sections

Exampletime24 function addTime ()time24 function addTime ()

Lecture 1 Lecture 1 – – Introduction: C++, Data StructuresIntroduction: C++, Data Structures

Scope Resolution OperatorScope Resolution Operator

Rectangle Class ExampleRectangle Class Example

APIs and ExampleAPIs and Example-Constructor-Operations-RandomNumber Class

Generating Random NumbersGenerating Random Numbers

String Functions and String Functions and OperationsOperations

2

Data Structures/AlgorithmsData Structures/Algorithms Programs = Data Structures + Algorithms (Wirth)

– Importance – write program w/o either

Data Structures – (efficient) storage and manipulation of data sets

– Arrays, strings, lists, stacks, trees

Algorithms– Find, insert, erase, sort

“Efficient”?– Quantify (Lord Kelvin)– Space – Speed – Want machine independent metrics – Big-O notation

3

Algorithm ComplexityAlgorithm Complexity Big-O notation – machine-independent means for

determining efficiency of algorithm Idea: relate # of key operations or stmts to input size

– op count == 9N2 + 43N + 7, alg. is O(N2)– Concerned with asymptotic behavior

Can analyze– Best case – limited use– Average– Worst (default) – maximum # of ops.

E.g.: for (i = 0; i < N; i++) // linear search if (A[i] == searchValue) break;

Complexity of linear search?– O(N)

4

Standard LibraryStandard Library Languages include data structure/algorithms

– Java: ?– Java Collections Framework (ArrayList, TreeSet)– C++: Standard Template Library (string, list, set)– X.NET: .NET class library

Standard C++ includes C++ Standard Library Standard Template Library (STL) – part of Standard

Library that provides– Container classes implement DS/Alg

vector, deque, list set, map, multiset, multimap stack, queue, priority_queue array, valarray, string, bitset (“near containers”)

– Algorithms (not associated w/class) accumulate copy sort

5

Storage Containers Storage Containers (Vectors)(Vectors)

vector – indexing feature of array and can dynamically grow

#include <vector>

// Output elements of v

for (size_t i = 0; i < v.size (); ++i)

cout << v[i] << " “;

Output: 7 4 9 3 1

6

Storage Containers Storage Containers (Vectors)(Vectors)

vector -- “super-array”; all familiar array algorithms work

Grow or shrink vectors (std::vector<Type>)

7 4 9

7 4 9 3 1 0 0 0

7 4 9 3

vec to r v (w ith 5 e lem en ts )

v.res ize (8 ); (gro w to 8 e lem en ts )

1

v.res ize (3 ); (sh rin k to 3 e lem en ts )

7

Storage Containers Storage Containers (Vectors)(Vectors)

Vectors allow subscripting, but are inefficient storage structures for– insertions at arbitrary positions in a list – deletions at arbitrary positions in a list

3 0 3 51 5 2 0 3 0 3 5

1 5 2 0 3 0 3 51 5 2 0 3 0 3 5 4 0

4 02 5

4 0

1 5 4 0

2 0

8

3 0 3 51 5 2 0 3 0 3 5

1 5 2 0 3 0 3 51 5 2 0 3 0 3 5 4 0

4 02 5In sert 2 5 a t

P o s it io n 2

V ecto r 4 0

1 5 4 0

2 0

E rase 2 0 a tP o s it io n 1

V ecto r

S h ift righ t S h ift le ft

Shifting Elements

9

Storage Containers Storage Containers (Lists)(Lists)

list container (#include <list>)– Each element has reference that identifies

the next (and previous)– Adding a new item -- breaking a link in the

chain and creating two new links (O(1))

fro n t re a r

/ /

n e w Ite m

10

Storage Containers Storage Containers (Maps, Sets)(Maps, Sets)

maps and sets store keys (<set>, <map>) Use a binary search tree to store data Store data by key

TV 93

W 29Z

N T2P

D 29Z

F A 27

B 40A

R o o t

G 9B 7

H 14K

11

A BST Holding Airbill NumbersA BST Holding Airbill Numbers N = 8 -- any search requires at most 3

movements along a path from the root

TV 93

W 29Z

N T2P

D 29Z

F A 27

B 40A

R o o t

G 9B 7

H 14K

12

Abstract Data TypesAbstract Data Types Specify DS/Alg using ADTs ADT

– Collection of values (integers)– Set of operations on the data with pre- and post-

conditions (+, -, *, etc.)

In C++, we implement ADT’s with a class Class encapsulates

– Data – data members (Java: instance vars.)– Operations – member functions (Java: methods)

13

Abstract Data TypesAbstract Data Types

ADT Operation Description operationName: action statement specifies

input parameters, type of operation on elements of data structure, and output parameter(s)

Preconditions: necessary conditions that must apply to input parameters and current state of object to allow successful execution of operation

Postconditions: changes in data of structure caused by operation

14

Abstract Data TypesAbstract Data Types(time24)(time24)

duration (t): Time t is input parameter of type time24. Measure length of time from this time to time t and return result as a time24 value

Precondition: Time t must not be earlier than the current time

Consider:

9 30 10 20(a)

(b)

Time (Before) Time (After)

Operation:ct.addTime (50)

14

Current Time

16 15

Time t

Operation:ct.duration (t)

1 30

Return time

45

15

ClassesClasses(To implement ADTs)(To implement ADTs)

CLASS className Declaration class className { public: // <public member function prototypes> . . . . . . . . private: // <private data members> . . . . . . . . // <private member function prototypes> . . . . . . . . };

16

Classes Classes (Private/Public Sections)(Private/Public Sections)

public and private sections in a class definition allow program statements outside the class different access levels

pr i vate :

data m e m be rsm e m be r func t io ns

publ i c :

a c c e s s ib le to theim ple m e nta tion of

the m e m be r func tionsac c e s s ible by

any pro gram s tate m e ntdata m e m be rsm e m be r func t io ns

17

Classes Classes (Private/Public Sections)(Private/Public Sections)

Public members of a class are the interface of the object to the program.– Any statement with access to an object can access

a public member of the object

publ i c :

a c c e s s ib le to theim ple m e nta tion of

the m e m be r func tionsac c e s s ible by

any pro gram s tate m e ntdata m e m be rsm e m be r func t io ns

18

Classes Classes (Private/Public Sections)(Private/Public Sections)

Private section typically contains the data values of the object and utility (helper) functions that support class implementation– Only member functions of the class may access

elements in the private section– Key to separate implementation from interface

pr i vate :

data m e m be rsm e m be r func t io nsa c c e s s ib le to the

im ple m e nta tion ofthe m e m be r func tions

19

Scope Resolution OperatorScope Resolution Operator Binary scope resolution operator: "::“

– Signals the compiler that the function is a member of class– 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

Could also inline definition in class definition

returnType

className::functionName (argument list)

{

<C++ statements>

}

20

Class ExampleClass Example Class “Rectangle” Default constructor

– default arguments– member initializers

Const member functions (cannot modify object) Method definitions are inlined

– Usu. separate header from implementation

21

CLASS Rectangle Declaration

class Rectangle {public:// Ctor. Init length and widthRectangle(double length = 0.0, double width = 0.0): m_length (length),

m_width (width){}

22

CLASS Rectangle Declaration

// Return areadouble

area() const{ return m_length * m_width;

}  // Return perimeter

double perimeter() const

{ return 2 * (m_length + m_width);

}

23

CLASS Rectangle Declaration

// Change dimensionsvoid

setSides (double length, double width){m_length = length;m_width = width;

}  // Return length

double getLength() const

{ return m_length;

}

24

CLASS Rectangle Declaration

// return the width of the rectangledouble

getWidth() const{ return m_width;

} private:double m_length;double m_width;

};

25

APIsAPIs Application Programming Interface (API) =

ADT + syntax Documentation from ADT and class declaration

that captures key info– Function prototypes for all public member functions– Constructors usu. listed separately– Description of methods with pre- and post-

conditions

26

APIAPI(Constructor)(Constructor)

CLASS className Constructors “<file>.h”

className (<arguments>);Initializes the attributes of the object

Postconditions: Initial status of the object

27

API API (Operations)(Operations)

CLASS className Operations “<file>.h”

returnType functionName (argument list);Description of the action of the function and any return value

Preconditions: Necessary state of the object before executing the operation. Any

exceptions that are thrown when an error is detected.

Postconditions: State of the data items in the object after executing the operation ….

28

API ExampleAPI Example Random number class (not std C++) Generate integer and real random #’s Note API does not expose implementation

29

API API (RandomNumber Class)(RandomNumber Class)

CLASS RandomNumber Constructors

RandomNumber (unsigned int seed = 0);Sets the seed for the random number

generatorPostconditions: With the default value 0, the system clock initializes the seed; otherwise the user provides the seed for the generator

30

API API (RandomNumber Class)(RandomNumber Class)

CLASS RandomNumber Operations

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

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

231-1int random (unsigned int n);

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

31

Generating Random NumbersGenerating Random Numbers

int item; double x; RandomNumber rndA, rndB;

for (size_t i = 0; i < 5; ++i){item = rndA.random (40);// 0 <= item < 40

x = rndB.frandom ();// 0.0 <= x < 1.0

cout << item << " " << x;}

32

String MethodsString Methods Class string: useful member functions

– find_first_of– find_last_of– find– substr– insert– erase– string::npos

Free operator+ to concatenate Check string docs on course page

– SGI link

33

String Functions and OperationsString Functions and Operations

size_t

find_first_of (char c, size_t start = 0):

Look for the first occurrence of cc in the string beginning at index startstart. Return the index of the match if it occurs; otherwise returns static_cast<size_t> (-1) which is string::npos.

By default, startstart is 0 and the function searches the entire string.

34

String Functions and OperationsString Functions and Operations

size_t

find_last_of (char c):

Look for the last occurrence of cc in the string. Return the index of the match if it occurs; otherwise returns npos.

Since the search seeks a match in the tail of the string, no starting index is provided.

35

String Functions and OperationsString Functions and Operations

string

substr (size_t start = 0, size_t count = npos):Copy count characters from the string beginning at index startstart and return the characters as a substring. If the tail of the string has fewer than count characters or count is npos, the copy stops at end-of-string.

By default, startstart is 0 and the function copies characters from the beginning of the string. Also by default, the function copies the tail of the string.

36

String Functions and OperationsString Functions and Operations

size_t

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

The search takes string ss and index start and looks for a match of ss as a substring. Return the index of the match if it occurs; otherwise return npos.

By default, startstart is 0 and the function searches the entire string.

37

String Functions and OperationsString Functions and Operations

string& insert (size_t start, const string& s):Place the substring ss into the string beginning at index startstart. The insertion expands the size of the original string.

38

String Functions and OperationsString Functions and Operations

string&

erase (size_t start = 0, size_t count = npos):

Delete count characters from the string beginning at index startstart. If fewer than count characters exist or count is npos, delete up to end-of-string.

By default, startstart 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 truncate the string to the empty string with length 0