Presentation is loading. Please wait.

Presentation is loading. Please wait.

Abstract Data Types Applied Arrays: Lists and Strings Chapter 12 - 13.

Similar presentations


Presentation on theme: "Abstract Data Types Applied Arrays: Lists and Strings Chapter 12 - 13."— Presentation transcript:

1 Abstract Data Types Applied Arrays: Lists and Strings Chapter 12 - 13

2 ENUMERATION Type  A data type is a set of values together with a set of operations on those values.  In order to define a new simple data type, called enumeration type, we need three things:  A name for the data type.  A set of values for the data type.  A set of operations on the values.  C++ allows the user to define a new simple data type by specifying its name and the values, but not the operations.  The values that we specify for the data type must be identifiers.

3 The syntax for enumeration type is: enum typeName{value1, value2,...}; where value1, value2, … are identifiers.  value1, value2, … are called enumerators.  In C++, enum is a reserved word.  Enumeration type is an ordered set of values.

4 Example: enum colors{brown, blue, red, green, yellow}; defines a new data type, called colors  The values belonging to this data type are brown, blue, red, green, and yellow. Example: enum standing{freshman, sophomore, junior, senior}; defines standing to be an enumeration type.  The values belonging to standing are freshman, sophomore, junior, and senior.

5 Example: The following are illegal enumeration types because none of the values is an identifier. //Illegal enumeration types enum grades{'A', 'B', 'C', 'D', 'F'}; enum places{1st, 2nd, 3rd, 4th}; The following are legal enumeration types: enum grades{A, B, C, D, F}; enum places{first, second, third, fourth};

6  If a value has already been used in one enumeration type, it cannot be used by any other enumeration type in the same block.  The same rules apply to enumeration types declared outside of any blocks. Example: enum mathStudent{John, Bill, Cindy, Lisa, Ron}; enum compStudent{Susan, Cathy, John, William}; //Illegal  Suppose that these statements are in the same program in the same block.  The second enumeration type, compStudent, is not allowed because the value John was used in the previous enumeration type mathStudent.

7 Declaring Variables The syntax for declaring variables is the same as before, that is, dataType identifier, identifier,...;  The following statement defines an enumeration type sports enum sports{basketball, football, hockey, baseball, soccer,volleyball};  The following statement declares variables of the type sports. sports popularSport, mySport;

8 Assignment  The statement popularSport = football; stores football in popularSport  The statement mySport = popularSport; copies the content of popularSport in mySport.

9 Operations on Enumeration Types  No arithmetic operation is allowed on enumeration type.  The following statements are illegal; mySport = popularSport + 2; //illegal popularSport = football + soccer; //illegal popularSport = popularSport * 2; // illegal  Also, the increment and decrement operations are not allowed on enumeration types.  The following statements are illegal; popularSport++; //illegal popularSport--; //illegal

10  To increment the value of popularSport by 1, we can use the cast operator as follows: popularSport = static_cast (popularSport + 1);  Consider the following statements: popularSport = football; popularSport = static_cast (popularSport + 1);  After the second statement, the value of popularSport will be hockey.  The following statements results in storing basketball in popularSport. popularSport = football; popularSport = static_cast (popularSport - 1);

11 Relational Operators Suppose we have the enumeration type sports and the variables popularSport and mySport as defined above. Then football <= soccer is true hockey > basketball is true baseball < football is false If popularSport = soccer; mySport = volleyball; then popularSport < mySport is true

12 Enumeration Types and Loops Suppose mySport is a variable as declared above. for(mySport = basketball; mySport (mySport+1))... This for loop executes 5 times.

13 Input/Output of Enumeration Types  Input and output are defined only for built-in data types such as int, char, double.  The enumeration type can be neither input nor output (directly).  You can input and output enumeration indirectly

14 Example: enum courses{algebra, basic, pascal, cpp, philosophy, analysis, chemistry, history}; courses registered; char ch1,ch2; cin>>ch1>>ch2; //read two characters switch(ch1) { case 'a': if(ch2 == 'l') registered = algebra; else registered = analysis; break; case 'b': registered = basic; break;

15 case 'c': if(ch2 == 'h') registered = chemistry; else registered = cpp; break; case 'h': registered = history; break; case 'p': if(ch2 == 'a') registered = pascal; else registered = philosophy; break; default: cout<<"Illegal input."<<endl; }

16 Enumeration type can be output indirectly as follows: switch(registered) { case algebra: cout<<"algebra"; break; case analysis: cout<<"analysis"; break; case basic: cout<<"basic"; break; case chemistry: cout<<"chemistry"; break; case cpp: cout<<"cpp"; break; case history: cout<<"history"; break; case pascal: cout<<"pascal"; break; case philosophy: cout<<"philosophy"; }

17 enum courses{algebra, basic, pascal, cpp, philosophy, analysis, chemistry, history}; courses registered;  If you try to output the value of an enumerator directly, the computer will output the value assigned to the enumerator.  Suppose that registered = algebra;  The following statement outputs the value 0 because the (default) value assigned to algebra is 0: cout<<registered<<endl;  The following statement outputs 4 : cout<<philosophy<<endl;

18 Functions and Enumeration Types  Enumeration type can be passed as parameters to functions either by value or by reference.  A function can return a value of the enumeration type. courses readCourses() { courses registered; char ch1,ch2; cout<<"Enter the first two letters of the course: "<<endl; cin>>ch1>>ch2; switch(ch1) { case 'a': if(ch2 == 'l') registered = algebra; else registered = analysis; break;

19 case 'b': registered = basic; break; case 'c': if(ch2 == 'h') registered = chemistry; else registered = cpp; break; case 'h': registered = history; break; case 'p': if(ch2 == 'a') registered = pascal; else registered = philosophy; break; default: cout<<"Illegal input."<<endl; } //end switch return registered; } //end readCourses

20 void printEnum(courses registered) { switch(registered) { case algebra: cout<<"algebra"; break; case analysis: cout<<"analysis"; break; case basic: cout<<"basic"; break; case chemistry: cout<<"chemistry"; break; case cpp: cout<<"cpp"; break; case history: cout<<history"; break; case pascal: cout<<"pascal"; break; case philosophy: cout<<"philosophy"; } //end switch } //end printEnum

21 Declaring Variables When Defining the Enumeration Type enum grades{A,B,C,D,F} courseGrade; enum coins{penny, nickel, dime, halfDollar, dollar} change, usCoins;

22 Anonymous Data Types  A data type in which values are directly specified in the variable declaration with no type name is called an anonymous type. enum {basketball, football, baseball, hockey} mysport;  Creating an anonymous type has drawbacks.  We cannot pass an anonymous type as a parameter to a function.  A function cannot return a value of an anonymous type.  Values used in one anonymous type can be used in another anonymous type, but variables of those types are treated differently. enum {English, French, Spanish, German, Russian} languages; enum {English, French, Spanish, German, Russian} foreignLanguages; languages = foreignLanguages; //illegal

23 The typedef Statement  In C++, you can create synonyms or aliases to a previously defined data type by using the typedef statement.  The general syntax of the typedef statement is typedef existingTypeName newTypeName;  In C++, typedef is a reserved word.  The typedef statement does not create any new data type; it creates only an alias to an existing data type.

24 Example:  The following statement creates an alias, integer, for the data type int. typedef int integer;  The following statement creates an alias, real, for the data type double. typedef double real;  The following statement creates an alias, decimal, for the data type double. typedef double decimal;

25 Example: typedef int Boolean;//Line 1 const Boolean True = 1; //Line 2 const Boolean False = 0; //Line 3 Boolean flag;//Line 4  The statement at Line 1 creates an alias, Boolean, for the data type int.  The statements at Lines 2 and 3 declare the named constants True and False and initialize them to 1 and 0, respectively.  The statement at Line 4 declares flag to be a variable of the type Boolean.  Because flag is a variable of the type Boolean, the following statement is legal: flag = True;

26 The string Type To use the data type string, the program must include the header file string #include The statement string name = "William Jacob"; declares name to be string variable and also initializes name to "William Jacob". The position of the first character, 'W', in name is 0, the position of the second character, 'i', is 1, and so on. The variable name is capable of storing (just about) any size string.

27 Binary operator + (to allow the string concatenation operation), and the array index (subscript) operator [], have been defined for the data type string. Suppose we have the following declarations. string str1, str2, str3; The statement str1 = "Hello There"; stores the string "Hello There" in str1. The statement str2 = str1; copies the value of str1 into str2.

28 If str1 = "Sunny", the statement str2 = str1 + " Day"; stores the string "Sunny Day" into str2. If str1 = "Hello" and str2 = "There". then str3 = str1 + " " + str2; stores "Hello There" into str3. This statement is equivalent to the statement str3 = str1 + ' ' + str2;

29 The statement str1 = str1 + "Mickey"; updates the value of str1 by appending the string "Mickey" to its old value. If str1 = "Hello there", the statement str1[6] = 'T'; replaces the character t with the character T.

30 The data type string has a data type, string::size_type, and a named constant, string::npos, associated with it. string::size_typeAn unsigned integer (data) type string::npos The maximum value of the (data) type string::size_type, a number such as 4294967295 on many machines

31 The length Function The length function returns the number of characters currently in the string. The value returned is an unsigned integer. The syntax to call the length function is: strVar.length() where strVar is variable of the type string. The function length has no arguments.

32 Consider the following statements: string firstName; string name; string str; firstName = "Elizabeth"; name = firstName + " Jones"; str = "It is sunny."; StatementEffect cout<<firstName.length()<<endl; Outputs 9 cout<<name.length()<<endl; Outputs 15 cout<<str.length()<<endl; outputs 12

33 The function length returns an unsigned integer. The value returned can be stored in an integer variable. Since the data type string has the data type string::size_type associated with it, the variable to hold the value returned by the length function is usually of this type. string::size_type len; StatementEffect len = firstName.length(); The value of len is 9 len = name.length(); The value of len is 15 len = str.length();The value of len is 12

34 The size Function The function size is same as the function length. Both these functions return the same value. The syntax to call the function size is: strVar.size() where strVar is variable of the type string. As in the case of the function length, the function size has no arguments.

35 The find Function The find function searches a string to find the first occurrence of a particular substring and returns an unsigned integer value (of type string::size_type ) giving the result of the search. The syntax to call the function find is: strVar.find(strExp) where strVar is a string variable and strExp is a string expression evaluating to a string. The string expression, strExp, can also be a character. If the search is successful, the function find returns the position in strVar where the match begins. For the search to be successful, the match must be exact. If the search is unsuccessful, the function returns the special value string::npos ( “not a position within the string”).

36 The following are valid calls to the function find. str1.find(str2) str1.find("the") str1.find('a') str1.find(str2+"xyz") str1.find(str2+'b')

37 string sentence; stringstr; string::size_type position; sentence = "It is cloudy and warm."; str = "cloudy"; StatementEffect cout<<sentence.find("is")<<endl;Outputs 3 cout<<sentence.find("and")<<endl;Outputs 13 cout<<sentence.find('s')<<endl;Outputs 4 cout<<sentence.find(str)<<endl;Outputs 6 cout<<sentence.find("the")<<endl;Outputs the value of string::nops position = sentence.find("warm");Assigns 17 to position

38 The substr Function The substr function returns a particular substring of a string. The syntax to call the function substr is: strVar.substr(expr1,expr2) where expr1 and expr2 are expressions evaluating to unsigned integers. The expression expr1 specifies a position within the string (starting position of the substring). The expression expr2 specifies the length of the substring to be returned.

39 string sentence; stringstr; sentence = "It is cloudy and warm."; Statement Effect cout<<sentence.substr(0,5) Outputs: It is <<endl; cout<<sentence.substr(6,6) Outputs: cloudy <<endl; cout<<sentence.substr(6,16) Outputs: cloudy and warm. <<endl; cout<<sentence.substr(3,6) Outputs: is clo <<endl; str = sentence.substr(0,8); str = "It is cl" str = sentence.substr(2,10); str = " is cloudy"

40 The Function swap  The function swap is used to swap the contents of two string variables.  The syntax to use the function swap is strVar1.swap(strVar2) ; where strVar1 and strVar2 are string variables.  Suppose you have the following statements: string str1 = "Warm"; string str2 = "Cold";  After the following statement executes, the value of str1 is "Cold" and the value of str2 is "Warm". str1.swap(str2);

41 isVowel Function isVowel bool isVowel(char ch) { switch(ch) { case 'A': case 'E': case 'I': case 'O': case 'U': case 'Y': case 'a': case 'e': case 'i': case 'o': case 'u': case 'y': return true; default: return false; }

42 Function rotate  This function takes a string as a parameter, removes the first character of the string, and places it at the end of the string.  This is done by extracting the substring starting at position 1 until the end of the string, and then adding the first character of the string. string rotate(string pStr) { int len = pStr.length(); string rStr; rStr = pStr.substr(1,len - 1) + pStr[0]; return rStr; }

43 Things about Strings Made up of individual characters Denoted by double quotes Have invisible character at end called “null terminator character” (‘\0’) How many characters in the word “cat”?

44 44 String in C++ A string is an array of characters which contains a non-printing null character ‘\0’ ( with ASCII value 0 ) marking its end. A string can be initialized in its declaration in two equivalent ways. char message [ 8 ] = { ‘H’, ‘e’, ‘l’, ‘l’, ‘o’, ‘\0’ }; char message [ 8 ] = “Hello” ; message [0] [1] [2] [3] [4] [5] [6] [7] ‘H’ ‘e’ ‘l’ ‘l’ ‘o’ ‘\0’

45 45 char vs. string ‘A’ has data type char and is stored in 1 byte “A” is a string of 2 characters and is stored in 2 bytes 5000 ‘A’ 6000 ‘A’ 6001 ‘\0’

46 46 Recall that... char message[8]; // this declaration allocates memory To the compiler, the value of the identifier message alone is the base address of the array. We say message is a pointer (because its value is an address). It “points” to a memory location. message [0] [1] [2] [3] [4] [5] [6] [7] ‘H’ ‘e’ ‘l’ ‘l’ ‘o’ ‘\0’ 6000

47 Declaring Strings Can do multiple ways: char charArray [255]; // set size of array to 255 char *charArray = “blah blah blah”; // sets charArray pointing to space that’s 15 big Both ways accomplish the same thing because both are pointers to memory

48 Reading String from the User Use cin to get a word char charArray [255]; cin >> charArray; Use cin.getline ( ) to get entire line of text cin.getline (charArray, 255);

49 setw( ) There is a danger when getting input User can type a string longer than the array you have set up This will result in a crash! (trying to go into someone else’s memory) Use setw( ) to solve! Example: cin >> setw (255) >> charArray; Ensure input does not exceed size of array

50 Printing Strings Simple: use cout to do this Example: cout << charArray << endl;

51 String Functions Whole library dedicated to strings #include strcpy (char *, char *) // returns a char * strcat (char *, char *) // returns a char * strcmp (char *, char *) // returns an int strtok (char *, char *) // returns char *

52 strcmp ( ) Used to compare two strings CANNOT TYPE: if (string1 == string2) Example: int result = strcmp (“Hello”, “World”); // if result < 0, then “hello” is < “world” // if result == 0, then “hello” has the same chars // if result > 0, then “hello” > “world” (but it’s not)

53 strtok ( ) Token - sequence of chars separated by some delimiter Example: When,in,the,course,of,human,events,it, becomes What are tokens? What is delimiter? Answer: the words! Answer: the comma - so we say this is a comma delimited string of tokens

54 Usage (Pass NULL for each successive call) #include void main ( ) { char charArray [ ] = “Hello to the World”; char *tokenPtr; tokenPtr = strtok (charArray, “ “); while (tokenPtr !=NULL) { cout << tokenPtr << endl; tokenPtr = strtok (NULL, “ “); } Notice the NULL! Output: Hello to the World

55 More Code void main ( ) { char charArray [ ] = “Hello to the World”; char *tokenPtr; tokenPtr = strtok (charArray, “e“); while (tokenPtr !=NULL) { cout << tokenPtr << endl; tokenPtr = strtok (NULL, “e“); } Output: H llo to th World

56 56 Recall that... char message[8]; // this declaration allocates memory To the compiler, the value of the identifier message alone is the base address of the array. We say message is a pointer (because its value is an address). It “points” to a memory location. message [0] [1] [2] [3] [4] [5] [6] [7] ‘H’ ‘e’ ‘l’ ‘l’ ‘o’ ‘\0’ 6000

57 End of Lecture Next Time, Lists and Lists as Abstract Data Types Program #3, Due 10/21 – The Battle Ship Game

58 58 Aggregate String I/O in C++ I/O of an entire string is possible using the array identifier with no subscripts and no looping. EXAMPLE char message [ 8 ] ; cin >> message ; cout << message ;

59 59 Extraction operator >> Extraction operator >> When using the extraction operator ( >> ) to read input characters into a string variable, the >> operator skips any leading white space characters such as blanks and new lines. It then reads successive characters into the array, and stops at the first trailing white space character. The >> operator adds the null character to the end of the string.

60 60 Example using >> char name [ 5 ] ; cin >> name ; Suppose input stream looks like this: J o e name [0] name [1] name [2] name [3] name [4] 7000 total number of elements in the array null character is added ‘J’ ‘o’ ‘e’ ‘\0’

61 61 Function get( ) Because the extraction operator stops reading at the first trailing white space, >> cannot be used to input a string with blanks in it. If your string’s declared size is not large enough to hold the input characters and add the ‘\0’, the extraction operator stores characters into memory beyond the end of the array. Use get function with 2 parameters to overcome these obstacles. char message [ 8 ] ; cin.get (message, 8) ; // inputs at most 7 characters plus ‘\0’

62 62 inFileStream.get ( str, count + 1) get does not skip leading white space characters such as blanks and new lines. get reads successive characters (including blanks) into the array, and stops when it either has read count characters, or it reaches the new line character ‘\n’, whichever comes first. get appends the null character to str. If it is reached, new line is not consumed by get, but remains waiting in the input stream.

63 63 Function ignore( ) can be used to consume any remaining characters up to and including the new line ‘\n’ left in the input stream by get cin.get ( string1, 81 ) ; // inputs at most 80 characters cin.ignore ( 30, ‘\n’ ) ; // skips at most 30 characters // but stops if ‘\n’ is read cin.get ( string2, 81 ) ;

64 64 Another example using get( ) char ch ; char fullName [ 31 ] ; char address [ 31 ] ; cout << “Enter your full name: “ ; cin.get ( fullName, 31 ) ; cin.get (ch) ; // to consume the new line cout << “Enter your address: “ ; cin.get ( address, 31 ) ; fullName [0] ‘N’ ‘e’ ‘l’ ‘l’ ‘ ’ ‘D’ ‘a’ ‘l’ ‘e’ ‘\0’... address [0] ‘A’ ‘u’ ‘s’ ‘t’ ‘i‘ ‘n’ ‘ ’ ‘T’ ‘X’ ‘\0’...

65 65 String function prototypes in String function prototypes in int strlen (char str [ ] ); // FCTNVAL == integer length of string str ( not including ‘\0’ ) int strcmp ( char str1 [ ], char str2 [ ] ); // FCTNVAL== negative, if str1 precedes str2 lexicographically //== positive, if str1 follows str2 lexicographically //== 0, if str1 and str2 characters same through ‘\0’ char * strcpy ( char toStr [ ], char fromStr [ ] ); // FCTNVAL== base address of toStr ( usually ignored ) // POSTCONDITION : characters in string fromStr are copied to //string toStr, up to and including ‘\0’, //overwriting contents of string toStr

66 # include. char author [ 21 ] ; int length ; cin.get ( author, 21 ) ; length = strlen ( author ) ; // What is the value of length ? 5000 author [0] ‘C’ ‘h’ ‘i’ ‘p’ ‘ ’ ‘W’ ‘e’ ‘e’ ‘m’ ‘s’ ‘\0’....

67 char myName [ 21 ] = “Huang” ; // WHAT IS OUTPUT? char yourName [ 21 ] ; cout << “Enter your last name : “ ; cin.get ( yourName, 21 ) ; if ( strcmp ( myName, yourName ) == 0 ) cout << “We have the same name! “ ; else if ( strcmp ( myName, yourName ) < 0 ) cout << myName << “ comes before “ << yourName ; else if ( strcmp ( myName, yourName ) > 0 ) cout << yourName << “comes before “ << myName ; myName [0] ‘H’ ‘u’ ‘a’ ‘n’ ‘g’ ‘\0’... yourName [0] ‘H’ ‘e’ ‘a’ ‘d’ ‘i‘ ‘n’ ‘ g’ ‘t’ ‘o’ ‘n’ ‘\0’...

68 char myName [ 21 ] = “Huang” ; char yourName [ 21 ] ; if ( myName == yourName ) // compares addresses only! { // That is, 4000 and 6000 here.. // DOES NOT COMPARE CONTENTS!. } myName [0] ‘H’ ‘u’ ‘a’ ‘n’ ‘g’ ‘\0’... yourName [0] ‘H’ ‘e’ ‘a’ ‘d’ ‘i‘ ‘n’ ‘ g’ ‘t’ ‘o’ ‘n’ ‘\0’... 4000 6000

69 char myName [ 21 ] = “Huang” ; char yourName [ 21 ] ; cin.get ( yourName, 21 ) ; yourName = myName; // DOES NOT COMPILE! // What is the value of myName ? myName [0] ‘H’ ‘u’ ‘a’ ‘n’ ‘g’ ‘\0’... yourName [0] 4000 6000 ‘H’ ‘e’ ‘a’ ‘d’ ‘i‘ ‘n’ ‘ g’ ‘t’ ‘o’ ‘n’ ‘\0’...

70 char myName [ 21 ] = “Huang” ; char yourName [ 21 ] ; cin.get ( yourName, 21 ) ; strcpy ( yourName, myName ) ; // changes string yourName // OVERWRITES CONTENTS! myName [0] ‘H’ ‘u’ ‘a’ ‘n’ ‘g’ ‘\0’... yourName [0] ‘H’ ‘e’ ‘a’ ‘d’ ‘i‘ ‘n’ ‘ g’ ‘t’ ‘o’ ‘n’ ‘\0’... 4000 6000 ‘u’ ‘n’ ‘g’ ‘\0’

71 71 Using typedef with arrays typedef int Boolean ; // names Boolean as a data type typedef char String20 [ 21 ] ; // names String20 as an array type String20 myName ; // these declarations String20 yourName ; // allocate memory for 3 variables Boolean isSeniorCitizen ; 5000 7000 6000

72 72 Write a program that will... Read the ID numbers, hourly wages, and names, for up to 50 persons from a data file. Then display the ID number and hourly wage for any person in the file whose name is entered at the keyboard, or indicate that the person was not located, if that is the case.

73 73 Assume file has this form with data for no more than 50 persons 4562 19.68 Dale Nell 1235 15.75 Weems Chip 6278 12.71 Headington Mark... 8754 17.96 Cooper Sonia 2460 14.97 Huang Jeff

74 74 Parallel arrays hold related data const int MAX_PERSONS = 50; typedef char String20[ 21] ; // define data type. // declare 3 parallel arrays int idNums[ MAX_PERSONS ] ; float wages[ MAX_PERSONS ] ; String20 names[ MAX_PERSONS ] ; // holds up to 50 strings each with // up to 20 characters plus null character ‘\0’

75 75 idNums[ 0 ] 4562 wages[ 0 ] 19.68 names[ 0 ] “Dale Nell” idNums[ 1 ] 1235 wages[ 1 ] 15.75 names[ 1 ] “Weems Chip” idNums[ 2 ] 6278 wages[ 2 ] 12.71 names[ 2 ] “Headington Mark”...... idNums[ 48] 8754 wages[ 48] 17.96 names[ 48] “Cooper Sonia” idNums[ 49] 2460 wages[ 49] 14.97 names[ 49] “Huang Jeff” int idNums [ MAX_PERSONS ] ; // parallel arrays float wages [ MAX_PERSONS ] ; String20 names [ MAX_PERSONS ] ;

76 76 #include #include “bool.h” typedef char String20 [ 21 ] ; const int MAX_PERSONS = 50 ; void GetData ( int [ ], float [ ], String20 [ ], int & ) ; // prototypes void HandleRequests ( int [ ], float [ ], String20 [ ], int ) ; void LookUp ( String20 [ ], String20, int, Boolean &, int & ) ; Using array of strings

77 77 Main Program int main (void) { int idNums [MAX_PERSONS] ; // holds up to 50 IDs float wages [MAX_PERSONS] ; // holds up to 50 wages String20 names [MAX_PERSONS] ; // holds up to 50 names int numPersons; // number of persons’ information in file GetData ( idNums, wages, names, numPersons ) ; HandleRequests ( idNums, wages, names, numPersons ) ; cout << “End of Program.\n”; return 0 ; }

78 78 Module Structure Chart Main GetData LookUp HandleRequests names oneName numPersons idNums wages names numPersons idNums wages names numPersons found index

79 void GetData ( /* out */ int ids[ ], /* out*/ float wages[ ], /* out */ String20 names[ ], /* out */ int & howMany ) {ifstream myInfile ; // Reads data from data file int k = 0 ; char ch ; myInfile.open (“A:\\my.dat”) ; if ( ! myInfile ) { cout << “File opening error. Program terminated! “ << endl ; exit ( 1 ) ; } myInfile >> ids[ k ] >> wages [k] ; // get information for first person myInfile.get(ch) ; // read blank myInfile.get (names[ k ], 21) ; myInfile.ignore(30, ‘\n’) ; // consume newline while (myInfile) // while the last read was successful { k++ ; myInfile >> ids[ k ] >> wages [k] ; myInfile.get(ch) ; // read blank myInfile.get (names[ k ], 21) ; myInfile.ignore(30, ‘\n’) ; // consume newline } howMany = k; }

80 void HandleRequests( const /* in */ int idNums[ ], const /* in */ float wages[ ], const /* in */ String20 names[ ], /* in */ int numPersons ) { String20 oneName ; // string to hold name of one person int index ; // will hold an array index value char response; // user’s response whether to continue Boolean found; // has oneName been located in array names do {cout << “Enter name of person to find: ” ; cin.get (oneName, 21) ; cin.ignore (100, ‘\n’);// consume newline LookUp (names, oneName, numPersons, found, index ); if ( found ) cout << oneName << “ has ID # “ << idNums [index] << “ and hourly wage $ “ << wages [index] << endl; else cout << oneName << “ was not located. “ << endl; cout << “Want to find another (Y/N)? “; cin >> response ; response = toupper ( response ); } while ( response == ‘Y’ ); }

81 void LookUp ( const /* in */ String20 names [ ], const /* in */ String20 oneName, /* in */ int numPersons, /* out */ Boolean & found, /* out */ int & index) // Sequential search of unordered array. // POSTCONDITION: // IF oneName is in names array // found == true && names[index] == oneName // ELSE // found == false && index == numPersons { index = 0; found = false; // initialize flag while ( ( ! found ) && ( index < numPersons ) ) // more to search { if ( strcmp ( oneName, names[index] ) == 0 ) // match here found = true ; // change flag else index ++ ; }

82 82 Ways to improve efficiency of searching process If the array names were sorted, the sequential search for oneName could be aborted as soon as a single name with greater lexicographic (dictionary) order is examined. If the array names were sorted, a faster type of search, called a binary search, could be used instead of the slower sequential search.

83 83 Sorting means arranging the list elements into some order (for instance, strings into alphabetical order, or numbers into ascending or descending order). sorting Dale Nell Weems Chip Headington Mark Cooper Sonia Huang Jeff Cooper Sonia Dale Nell Headington Mark Huang Jeff Weems Chip

84 84 Selection Sort Process examines the entire list to select the smallest element. Then places that element where it belongs (with array subscript 0). examines the remaining list to select the smallest element from it. Then places that element where it belongs (with array subscript 1).. examines the last 2 remaining list elements to select the smallest one. Then places that element where it belongs in the array.

85 85 Selection Sort Algorithm FOR pass going from 0 through length - 2 Find minimum value in list [ pass.. length-1 ] Swap minimum value with list [ pass ] length = 5 names [ 0 ] Dale Nell Cooper Sonia names [ 1 ] Weems Chip Weems Chip names [ 2 ] Headington Mark Headington Mark names [ 3 ] Cooper Sonia Dale Nell names [ 4 ] Huang Jeff Huang Jeff pass = 0

86 void SelSort ( /* inout */ String20 names [ ], /* in */ int length ) // Selection sorts names into alphabetic order // Preconditions: length <= MAX_PERSONS // && names [0.. length -1 ] are assigned // Postcondition: names [ 0.. length -1 ] are rearranged into order { int pass; int place; int minIndex; String20 temp; for ( pass = 0 ; pass < length - 1 ; pass++ ) { minIndex = pass; for ( place = pass + 1 ; place < length ; place ++ ) if ( strcmp ( names [ place ], names [ minIndex ] ) < 0 ) minIndex = place; //swap names[pass] with names[minIndex] strcpy ( temp, names [ minIndex ] ) ; strcpy ( names [ minIndex ], names [ pass] ) ; strcpy ( names [ pass ], temp ) ; }

87 87 Binary Search in an Ordered List Examines the element in the middle of the array. Is it the sought item? If so, stop searching. Is the middle element too small? Then start looking in second half of array. Is the middle element too large? Then begin looking in first half of the array. Repeat the process in the half of the list that should be examined next. Stop when item is found, or when there is nowhere else to look and it has not been located.

88 88 void BinSearch( /* in */ const ItemType list [ ], /* in */ ItemType item, /* in */ int length, /* out */ int& index, /* out */ Boolean & found ) // Searches list for item, returning index of item if found // Precondition: // list [0.. length - 1 ] are in ascending order // && length is assigned && item is assigned // // Postcondition: // IF item is in list // found == true && list[index] == item // ELSE // found == false && index is undefined Heading for BinSeach function

89 89 { int first = 0 ; // lower bound on list int last = length - 1 ; // upper bound on list int middle ; // middle index found = false ; while ( ( last >= first ) && (! found ) ) { middle = ( first + last ) / 2 ; if ( item < list [ middle ] ) last = middle - 1 ; // look in first half next else if ( item > list [ middle ] ) first = middle + 1; // look in second half next else found = true ; } index = middle ; } Body for BinSearch function

90 90 Trace of BinSearch function list[0] [1] [2] [3] [4] [5] [6] [7] [8] [9] 15 26 38 57 62 78 84 91 108 119 item = 45 first middle last list[0] [1] [2] [3] [4] [5] [6] [7] [8] [9] 15 26 38 57 62 78 84 91 108 119 first middle last item < list [ middle ] last = middle - 1 item > list [ middle ] first = middle + 1

91 91 Trace continued list[0] [1] [2] [3] [4] [5] [6] [7] [8] [9] 15 26 38 57 62 78 84 91 108 119 item = 45 first, middle, last list[0] [1] [2] [3] [4] [5] [6] [7] [8] [9] 15 26 38 57 62 78 84 91 108 119 first, last middle item > list [ middle ] first = middle + 1 item < list [ middle ] last = middle - 1

92 92 Trace concludes list[0] [1] [2] [3] [4] [5] [6] [7] [8] [9] 15 26 38 57 62 78 84 91 108 119 item = 45 last first last < first found = false

93 End of Lecture


Download ppt "Abstract Data Types Applied Arrays: Lists and Strings Chapter 12 - 13."

Similar presentations


Ads by Google