50
Data Structures and Algorithms in C++ Michael T. Goodrich Roberto Tamassia David M. Mount Chapter 1 Basic C++ Programming 1

Data Structures and Algorithms in C++  Michael T. Goodrich Roberto Tamassia David M. Mount

Embed Size (px)

DESCRIPTION

Data Structures and Algorithms in C++  Michael T. Goodrich Roberto Tamassia David M. Mount. Chapter 1 Basic C++ Programming. Contents. 1.1 Basic C++ Programming Elements 1.2 Expressions 1.3 Control Flow 1.4 Functions 1.5 Classes 1.6 C++ Program and File Organization - PowerPoint PPT Presentation

Citation preview

Page 1: Data Structures and Algorithms in C++  Michael T. Goodrich Roberto Tamassia David M. Mount

Data Structures and Algorithms in C++

Michael T. Goodrich Roberto Tamassia David M. Mount

Chapter 1Basic C++ Programming

1

Page 2: Data Structures and Algorithms in C++  Michael T. Goodrich Roberto Tamassia David M. Mount

Contents

• 1.1 Basic C++ Programming Elements• 1.2 Expressions• 1.3 Control Flow• 1.4 Functions• 1.5 Classes• 1.6 C++ Program and File Organization• 1.7 Writing a C++ Program• 1.8 Exercises

2

Page 3: Data Structures and Algorithms in C++  Michael T. Goodrich Roberto Tamassia David M. Mount

1.1 Basic C++ Programming Elements

1.1.1 A Simple C++ Program#include <cstdlib>#include <iostream>/* Inputs two numbers and outputs their sum */int main( ) {

int x , y;std::cout << “Please enter two numbers: “;std::cin >> x >> y; // inputs x and yint sum = x + y; // compute their sumstd::cout << “Their sum is “ << sum << std::endl;return EXIT_SUCCESS; // terminates successfully

}

3

Page 4: Data Structures and Algorithms in C++  Michael T. Goodrich Roberto Tamassia David M. Mount

1.1 Basic C++ Programming Elements

1.1.2 Fundamental Typesbool Boolean value, either true or falsechar charactershort, int, long short, normal, long integerfloat, double single-, double- precision

floating-point numbervoid nothingenumenum Color {RED, GREEN, BLUE}

4

Page 5: Data Structures and Algorithms in C++  Michael T. Goodrich Roberto Tamassia David M. Mount

1.1 Basic C++ Programming Elements

Pointers

char ch = ‘Q’;char* p = &ch;cout << *p;ch = ‘Z’;cout << *p;

5

Page 6: Data Structures and Algorithms in C++  Michael T. Goodrich Roberto Tamassia David M. Mount

1.1 Basic C++ Programming Elements

Arrays

double f[3];double* p[10];f[2] = 25.3;p[4] = &f[2];cout << *p[4];

6

Page 7: Data Structures and Algorithms in C++  Michael T. Goodrich Roberto Tamassia David M. Mount

1.1 Basic C++ Programming Elements

Strings

#include <string>using std::string;//…string s = “to be”;string t = “not “ + s;string u = s + “ or “ + t;if (s > t)

cout << u;

7

Page 8: Data Structures and Algorithms in C++  Michael T. Goodrich Roberto Tamassia David M. Mount

1.1 Basic C++ Programming Elements

C-Stype Structuresenum MealType { NO_PREF, REGULAR, LOW_FAT,

VEGETARIAN };struct Passenger {

string name;MealType mealPref;bool isFreqFlyer;string freqFlyerNo;

};

8

Page 9: Data Structures and Algorithms in C++  Michael T. Goodrich Roberto Tamassia David M. Mount

1.1 Basic C++ Programming Elements

Pointers, Dynamic Memory, and the “new” Operator

Passenger *p;//…p = new Passenger;p ->name = “Pocahontas”;p ->mealPref = REGULAR;p ->isFreqFlyer = false;p ->freqFlyerNo = “NONE”;

9

Page 10: Data Structures and Algorithms in C++  Michael T. Goodrich Roberto Tamassia David M. Mount

1.1 Basic C++ Programming Elements

1.1.4 Scope and Namespaces

Constants and Typedefconst int CUT_OFF[ ] = {90, 80, 70, 60};const int N_DAYS = 7;const int N_HOURS = 24*N_DAYS;int counter [N_HOURS];

10

Page 11: Data Structures and Algorithms in C++  Michael T. Goodrich Roberto Tamassia David M. Mount

1.1 Basic C++ Programming Elements

typedef char* BufferPtr;typedef double Coordinate;BufferPtr p;Coordinate x, y;

11

Page 12: Data Structures and Algorithms in C++  Michael T. Goodrich Roberto Tamassia David M. Mount

1.1 Basic C++ Programming Elements

Local and Global Scopes

const int cat = 1;int main ( ) {

const int cat = 2;cout << cat;return EXIT_SUCCESS;

}

int dog = cat;

12

Page 13: Data Structures and Algorithms in C++  Michael T. Goodrich Roberto Tamassia David M. Mount

1.1 Basic C++ Programming Elements

Namespacesnamespace myglobals {

int cat;string dog = “bow wow”;

}The Using Statement

using std::string;using std::cout;using namespace myglobals;

13

Page 14: Data Structures and Algorithms in C++  Michael T. Goodrich Roberto Tamassia David M. Mount

1.2 ExpressionsMember Selection and lndexing

class_name . member class/structure member selection

pointer -> member class/structure member selection

array [exp] array subscripting

14

Page 15: Data Structures and Algorithms in C++  Michael T. Goodrich Roberto Tamassia David M. Mount

1.2 ExpressionsArithmetic Operators

exp + exp additionexp – exp subtractionexp * exp multiplicationexp / exp divisionexp % exp modulo(remainder)

15

Page 16: Data Structures and Algorithms in C++  Michael T. Goodrich Roberto Tamassia David M. Mount

1.2 ExpressionsIncrement and Decrement Operators

var ++post incrementvar - - post decrement++ varpre increment- - var pre decrement

16

Page 17: Data Structures and Algorithms in C++  Michael T. Goodrich Roberto Tamassia David M. Mount

1.2 ExpressionsRelational and Logical Operators

exp < exp less thanexp > exp greater thanexp <= exp less than or equalexp >= exp greater than or equalexp == exp equal toexp != exp not equal to! exp logical not exp && exp logical andexp || exp logical or

17

Page 18: Data Structures and Algorithms in C++  Michael T. Goodrich Roberto Tamassia David M. Mount

1.2 ExpressionsBitwise Operators

~ exp bitwise complementexp & exp bitwise andexp ^ exp bitwise exclusibe-orexp | exp bitwise orexp1 << exp2 shift exp1 left by exp2 bitsexp1 >> exp2 shift exp1 right by exp2 bits

18

Page 19: Data Structures and Algorithms in C++  Michael T. Goodrich Roberto Tamassia David M. Mount

1.2 ExpressionsAssignment Operators

int i = 10;int j = 5;int k = 1;string s = “yes”;i - = 4;j *= -2;k <<= 1;s += “ or no”;

19

Page 20: Data Structures and Algorithms in C++  Michael T. Goodrich Roberto Tamassia David M. Mount

1.2 Expressions

class_name::membernamespace_name::memberbool_exp ? True_exp : false_expstream >> varstream << exp

20

Page 21: Data Structures and Algorithms in C++  Michael T. Goodrich Roberto Tamassia David M. Mount

1.2 Expressions1.2.1 Casting in ExpressionsTraditional C-Style Casting

int cat = 14;double dog = (double) cat;double pig = double(cat);

21

Page 22: Data Structures and Algorithms in C++  Michael T. Goodrich Roberto Tamassia David M. Mount

1.2 ExpressionsStatic Casting

Static_cast < <desired_type> > ( <expression> );

double d1 = 3.2;double d2 = 3.9999;int i1 = static_cast<int>(d1);int i2 = static_cast<int>(d2);

22

Page 23: Data Structures and Algorithms in C++  Michael T. Goodrich Roberto Tamassia David M. Mount

1.2 ExpressionsImplicit Casting

int = 3;double d = 4.8;double d3 = i / d;int i3 = d3;

23

Page 24: Data Structures and Algorithms in C++  Michael T. Goodrich Roberto Tamassia David M. Mount

1.3 Control FlowIf Statement

if (<boolean_exp>)<true_statement>

[else if (<boolean_exp>)<else_if_statement>]

[else<else_statement>]

24

Page 25: Data Structures and Algorithms in C++  Michael T. Goodrich Roberto Tamassia David M. Mount

1.3 Control FlowSwitch Statement

char command;cin >> command;switch (command){

case ‘I’ :editlnsert();break;

case ‘D’ :editDelete();break;

case ‘R’ :editReplace();break;

default :cout << “Unrecognized command\n”;break;

}25

Page 26: Data Structures and Algorithms in C++  Michael T. Goodrich Roberto Tamassia David M. Mount

1.3 Control FlowWhile and Do_While Loops

while (<boolean_expression>)<loop_body_statement>

do<loop_body_statement>

while ( <boolean_expression> )

26

Page 27: Data Structures and Algorithms in C++  Michael T. Goodrich Roberto Tamassia David M. Mount

1.3 Control FlowFor Loop

for ( [<initialization>]; [<condition>]; [<increment>] )<body_statement>

const int NUM_ELEMENTS = 100;float a[NUM_ELEMENTS];//…for (int i = 0 ; i < NUM_ELEMENTS; i++) {

if (a[i] > 0 ) { cout << a[i] << ‘\n’ ;}}

27

Page 28: Data Structures and Algorithms in C++  Michael T. Goodrich Roberto Tamassia David M. Mount

1.3 Control FlowBreak and Continue Statements

int sum = 0;while (true) {

int x;cin >> x;if ( x < 0 ) break;sum += x;

}cout << “Sum is “ << x << ‘\n’;

28

Page 29: Data Structures and Algorithms in C++  Michael T. Goodrich Roberto Tamassia David M. Mount

1.4 Fuctionsbool evenSum(int a[ ], int n );int main( ) {

const int listLength = 6;int list[ listLength ] = {4, 2, 7, 8, 5, 6};bool result = evenSum( list, listLength);if (result) cout << “even sum. \n”;else cout << “odd sum. \n”;return EXIT_SUCCESS;

}bool evenSum( int a[ ], int n) {

int sum = 0;for ( int i = 0 ; I < n ; i++ ) sum += a[ i ];return (sum % 2 ) == 0;

}

29

Page 30: Data Structures and Algorithms in C++  Michael T. Goodrich Roberto Tamassia David M. Mount

1.4 Fuctions1.4.1 Argument Passing

void f(int value, int &ref) {value++;ref++;cout << value << ‘\n’;cout << ref << ‘\n’;

}int main( ) {

int cat = 1;int dog = 5;f(cat, dog);cout << cat << ‘\n’;cout << dog << ‘\n’;return EXIT_SUCCESS;

}30

Page 31: Data Structures and Algorithms in C++  Michael T. Goodrich Roberto Tamassia David M. Mount

1.4 Fuctions1.4.2 OverloadingFunction Overloading

void print( int x ){ cout << x; }

void print( const Passenger &pass) {cout << pass.name << “ “ << pass.mealPref;if ( pass.isFreqFlyer ) {

cout << “ “ << pass.freqFlyerNo;}

}31

Page 32: Data Structures and Algorithms in C++  Michael T. Goodrich Roberto Tamassia David M. Mount

1.4 FuctionsOperator Overloading

bool operator == ( const Passenger &x, const Passenger &y ) {

return x.name == y.name&& x.mealPref == y.mealPref&& x.isFreqFlyer == y.isFreqFlyer&& x.FreqFlyerNo == y.FreqFlyerNo

}

32

Page 33: Data Structures and Algorithms in C++  Michael T. Goodrich Roberto Tamassia David M. Mount

1.4 FuctionsUsing Overloading

ostream& operator << (ostream &out, const Passenger &pass) {

out << pass.name << “ “ << pass.mealPref;if ( pass.isFreqFlyer ) {

out << “ “ << pass.freqFlyerNo;}return out;

}

33

Page 34: Data Structures and Algorithms in C++  Michael T. Goodrich Roberto Tamassia David M. Mount

1.5 Classes1.5.1 Class Structure

class Passerger {private:

string name;MealType mealPref;bool isFreqflyer;string freqFlyerNo;

public://…Passenger( );bool isFrequentFlyer( ) const

{ return isFreqFlyer; }void makeFrequentFlyer(const string& newFreqFlyerNo){

isFreqFlyer = true;freqFlyerNo = newFreqFlyerNo;

}} ; 34

Page 35: Data Structures and Algorithms in C++  Michael T. Goodrich Roberto Tamassia David M. Mount

1.5 Classes1.5.2 Constructors

class Passenger {private:

//…public:

Passenger( );Passenger( const string &nm, MealType mpref,

string ffn = “NONE” );passenger( const Passenger &pass) ;//…

};35

Page 36: Data Structures and Algorithms in C++  Michael T. Goodrich Roberto Tamassia David M. Mount

1.5 Classes1.5.2 Destructors

class Vect {private:

int* theVect;int vectSize;

public:Vect( int size = 10) {

vectSize = size;theVect = new int[ size ];

}//…~Vect( ){ delete [ ] theVect; }

} ;36

Page 37: Data Structures and Algorithms in C++  Michael T. Goodrich Roberto Tamassia David M. Mount

1.5 Classes1.5.3 Classes and Memory Allocation

Vect a(100);Vect b = a;Vect c;

c = a;

37

Page 38: Data Structures and Algorithms in C++  Michael T. Goodrich Roberto Tamassia David M. Mount

1.5 Classes

Vect::Vect (const Vect &a) {vectsize = a.vectSize;theVect = new int[ vectSize ];for (int i = 0; i < vectSize; i++ ) {

theVect[i] = a.theVect[i];}

}

38

Page 39: Data Structures and Algorithms in C++  Michael T. Goodrich Roberto Tamassia David M. Mount

1.5 Classes

Vect& Vect::operator = (const Vect &a) {if (this != &a) {

delete [ ] theVect;vectSize = a.vectSize; theVect = new int[ vectSize ];for (int i = 0; i < vectSize ; i++ ) {

theVect[ i ] = a.theVect[ i ];}

}return *this;

}39

Page 40: Data Structures and Algorithms in C++  Michael T. Goodrich Roberto Tamassia David M. Mount

1.5 Classes1.5.4 Class Friends and Class Members

class SomeClass {private:

int secret;public:

//…friend ostream& operator <<

(ostream &out, const SomeClass &x);};

ostream& operator <<(ostream &out, const SomeClass &x);{ cout << x.secret; }

40

Page 41: Data Structures and Algorithms in C++  Michael T. Goodrich Roberto Tamassia David M. Mount

1.5 ClassesNesting Classes and Types within Classes

class Complex {private:

class Node {//…

};//…

};41

Page 42: Data Structures and Algorithms in C++  Michael T. Goodrich Roberto Tamassia David M. Mount

1.5 Classes1.5.5 The Standard Template Library

stack Container with last-in, first-out accessqueue Container with first-in, first-out accessdeque Double-ended queuevector Resizeable arraylist Doubly linked listset Setmap Associative array ( dictionary)priority_queue Queue orderde by value

42

Page 43: Data Structures and Algorithms in C++  Michael T. Goodrich Roberto Tamassia David M. Mount

1.6 C++ Program and File OrganizationCreditCard.h#ifndef CREDIT_CARD_H #define CREDIT_CARD_H #include <string> #include <iostream> using std::string; class CreditCard { private:

string number;string name;int limit; double balance;

43

Page 44: Data Structures and Algorithms in C++  Michael T. Goodrich Roberto Tamassia David M. Mount

1.6 C++ Program and File Organizationpublic:

CreditCard(string no, string nm, int lim, double bal=0); string getNumber() const { return number; } string getName() const { return name; }

double getBalance() const { return balance; } int getLimit() const { return limit; }bool chargeIt(double price); void makePayment(double payment)

{ balance -= payment; } };std::ostream& operator<<(std::ostream& out,

const CreditCard& c); #endif 44

Page 45: Data Structures and Algorithms in C++  Michael T. Goodrich Roberto Tamassia David M. Mount

1.6 C++ Program and File OrganizationCreditCard.cpp#include "CreditCard.h“CreditCard::CreditCard(string no, string nm, int lim, double bal) { number = no;

name = nm; balance = bal; limit = lim;

}bool CreditCard::chargeIt(double price) { if (price + balance > double(limit))

return false; balance += price; return true;

}45

Page 46: Data Structures and Algorithms in C++  Michael T. Goodrich Roberto Tamassia David M. Mount

1.6 C++ Program and File Organizationstd::ostream& operator<<(std::ostream& out,

const CreditCard& c) { out << "Number = " << c.getNumber() << "\n"

<< "Name = " << c.getName() << "\n" << "Balance = " << c.getBalance() << "\n" << "Limit = " << c.getLimit() << "\n";

return out; }

46

Page 47: Data Structures and Algorithms in C++  Michael T. Goodrich Roberto Tamassia David M. Mount

1.6 C++ Program and File Organization

TestCard.cpp#include <vector>#include "CreditCard.h“using namespace std;void testCard() {

vector<CreditCard*> wallet(10);wallet[0] = new CreditCard("5391 0375 9387 5309", "John Bowman", 2500); wallet[1] = new CreditCard("3485 0399 3395 1954", "John Bowman", 3500); wallet[2] = new CreditCard("6011 4902 3294 2994", "John Bowman", 5000);

for (int j=1; j <= 16; j++) {wallet[0]->chargeIt(double(j));wallet[1]->chargeIt(2 * j);wallet[2]->chargeIt(double(3 * j));}

47

Page 48: Data Structures and Algorithms in C++  Michael T. Goodrich Roberto Tamassia David M. Mount

1.6 C++ Program and File Organization

cout << "Card payments:\n"; for (int i=0; i < 3; i++) {

cout << *wallet[i]; while (wallet[i]->getBalance() > 100.0) { wallet[i]->makePayment(100.0); cout << "New balance = " << wallet[i]->getBalance() << "\

n"; }

cout << "\n"; delete wallet[i];

} } int main() {

testCard(); return EXIT_SUCCESS;

}48

Page 49: Data Structures and Algorithms in C++  Michael T. Goodrich Roberto Tamassia David M. Mount

1.7 Writing a C++ Program

• DesignResponsibilityIndependenceBehaviors

• CodingReadability and Style

• Testing and Debugging

49

Page 50: Data Structures and Algorithms in C++  Michael T. Goodrich Roberto Tamassia David M. Mount

1.8 Exercises

• R-1.1• R-1.2• R-1.4• R-1.10• R-1.12

50