930 likes | 1.11k Views
Abstract Data Types Applied Arrays: Lists and Strings Chapter 12 - 13. 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.
E N D
Abstract Data TypesApplied Arrays: Lists and StringsChapter 12 - 13
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 enumerationtype, 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.
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.
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.
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};
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.
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;
Assignment • The statement popularSport = football; stores football in popularSport • The statement mySport = popularSport; copies the content of popularSport in mySport.
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
To increment the value of popularSport by 1, we can use the cast operator as follows: popularSport = static_cast<sports>(popularSport + 1); • Consider the following statements: popularSport = football; popularSport = static_cast<sports>(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<sports>(popularSport - 1);
Relational Operators Suppose we have the enumeration type sports and the variables popularSport and mySport as defined above. Then football <= soccer istrue hockey > basketball istrue baseball < football isfalse If popularSport = soccer; mySport = volleyball; then popularSport < mySport istrue
Enumeration Types and Loops Suppose mySport is a variable as declared above. for(mySport = basketball; mySport <= soccer; mySport = static_cast<sports>(mySport+1)) ... • This for loop executes 5 times.
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
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;
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; }
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"; }
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;
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;
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
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
Declaring Variables When Defining the Enumeration Type enum grades{A,B,C,D,F} courseGrade; enum coins{penny, nickel, dime, halfDollar, dollar} change, usCoins;
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
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.
Example: • The following statement creates an alias, integer, for the data type int. typedefint integer; • The following statement creates an alias, real, for the data type double. typedefdouble real; • The following statement creates an alias, decimal, for the data type double. typedefdouble decimal;
Example: typedefint 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;
The string Type • To use the data type string, the program must include the header file string #include <string> • 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.
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.
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;
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.
The data type string has a data type, string::size_type, and a named constant, string::npos, associated with it. string::size_type An unsigned integer (data) type string::npos The maximum value of the (data) type string::size_type, a number such as 4294967295 on many machines
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.
Consider the following statements: string firstName; string name; string str; firstName = "Elizabeth"; name = firstName + " Jones"; str = "It is sunny."; Statement Effect cout<<firstName.length()<<endl; Outputs 9 cout<<name.length()<<endl; Outputs 15 cout<<str.length()<<endl; outputs 12
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; Statement Effect 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
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.
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”).
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')
string sentence; string str; string::size_type position; sentence = "It is cloudy and warm."; str = "cloudy"; Statement Effect 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
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.
string sentence; string str; 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"
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);
FunctionisVowel 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': returntrue; default: returnfalse; } }
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; }
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”?
‘H’ ‘e’ ‘l’ ‘l’ ‘o’ ‘\0’ message [0] [1] [2] [3] [4] [5] [6] [7] 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” ;
5000 ‘A’ 6000 6001 ‘A’ ‘\0’ 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
6000 ‘H’ ‘e’ ‘l’ ‘l’ ‘o’ ‘\0’ message [0] [1] [2] [3] [4] [5] [6] [7] Recall that . . . char message[8]; // this declaration allocates memory To the compiler, the value of the identifier message aloneis the base address of the array. We say message is a pointer (because its value is an address).It “points” to a memory location.
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
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);
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
Printing Strings • Simple: use cout to do this • Example: cout << charArray << endl;