1 / 54

Basic Data Structures

Basic Data Structures. Overview We will learn how data of one type can be converted into data of another type using a cast We will begin working with some of more interesting data structures These collectively are called containers because they hold stuff In this group we will find

jeanniet
Download Presentation

Basic Data Structures

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Basic Data Structures • Overview • We will learn how data of one type can be converted into data of • another type using a cast • We will begin working with some of more interesting data • structures • These collectively are called containersbecause they hold stuff • In this group we will find • array • string • struct • union 1 January 2001

  2. Basic Data Structures • Type Conversions • Implicit Type Conversions • An implicit type conversion occurs when the compiler needs • to convert ….. • From data of one intrinsic type • To data of another intrinsic type • Implicit conversions that preserve values are commonly • called promotions 1 January 2001

  3. Basic Data Structures • Type Conversions • Implicit Type Conversions • Before an arithmetic operation is performed • Integral promotion is used to create ints • Out of shorter integer types and • Floating-point promotion to make doubles • Out of floats • Promotionswill notpromote to long or to long double 1 January 2001

  4. Basic Data Structures • Type Conversions • Implicit Type Conversions • The integral promotions are • char, signed char, unsigned char, • short int, or unsigned short int • Convert to int • bool converts to int • false becomes 0 and • true becomes 1 1 January 2001

  5. Basic Data Structures • Type Conversions • Implicit Type Conversions // declare some variables short myShort = 2; int myInt = 3; myInt = myShort; cout << myInt << endl; // prints 2 myInt = 3; myShort = myInt; cout << myInt << endl; // prints 3 myInt = 32767; myShort = myInt; cout << myShort << endl; // prints 37767 myInt = 100000; myShort = myInt; cout << myShort << endl; // prints -31072 1 January 2001

  6. Basic Data Structures • Type Conversions • Implicit Type Conversions • The first assignment of myInt to myShort is safe • myShort = myInt • …but it will probably generate a compiler warning, why???? • What will we display if we • Assign the value 65536 to the int then • Assign the int to the short • If we change value assigned to int to 100000, what will we print?? 1 January 2001

  7. Basic Data Structures • Type Conversions • Implicit Type Conversions • Floating point conversions are not guaranteed to preserve the • value so they are not called promotions • Converting a float to a double is safe • Converting a double to a float is only safe if the value in the • double will fit in the float • Floating point conversion to integer works fine as long as the • integer variable is large enough to hold the resulting value 1 January 2001

  8. Basic Data Structures • Type Conversions • Explicit Type Conversions • We’ve seen that type conversions • Can occur automatically implicitly, • or • Explicitly by the designer using a casting operation • There are two cast syntaxes in C++ • One is from C • The other is C++ only 1 January 2001

  9. Basic Data Structures • Type Conversions • Explicit Type Conversions • Suppose we encounter the following legacy code • cout • Senses the char data type • Switches to character mode • M appears on the screen • char data = 'M'; • cout << data << endl; 1 January 2001

  10. Basic Data Structures • Type Conversions • Explicit Type Conversions • If we really wanted the value corresponding to data • We can rewrite these lines as • Now cout • Senses the int data type • Switches to integer mode char data = 'M'; int displaydata; displaydata = data; cout << displaydata << endl; 1 January 2001

  11. Basic Data Structures • Type Conversions • Explicit Type Conversions • What we need is a way to tell the compiler to convert the char to • an int on the fly • Here is the C-style cast….. • char data = 'M'; • cout << (int)data << endl; 1 January 2001

  12. Basic Data Structures • Type Conversions • Explicit Type Conversions • The reasons for casting are varied • 1. To round a floating point to the nearest integer • 2. We might cast one type to another to produce particular • results • Casting for any other reasons should be avoided 1 January 2001

  13. Basic Data Structures • Arrays • An Array • Is a group of consecutive memory locations • Organized to hold a collection of values • Single data type • The values are not named but are accessed by position in • the array • Such access called • Indexing or Subscripting • Indexes represent memory addresses 1 January 2001

  14. Basic Data Structures • Arrays • Declaration…. • int myArray [10]; • syntax • type identifier [dimension] • type • Specifies the type of elements stored in array • identifier • Names the array • dimension • Specifies the number of elements of the named type stored in the array • dimension is always enclosed in [ ] • Must be 1 • Computable at compile time • Cannot be a variable 1 January 2001

  15. Basic Data Structures • Arrays • Array elements • Numbered beginning at 0 • The index values in the example array a[ ] are…. • 0 - 9 • Not • 1 - 10 • This is a very common source of programming error 1 January 2001

  16. Basic Data Structures • Arrays • Schematically an array ‘a’ in memory looks like • Since each element of a[ ] is an int • On a 16 bit machine a[ ] requires 160 bits memory • If a[10] is placed into memory address 300000 • a[0] 300000 – 30FFFF • a[1] 310000 – 31FFFF •  •  •  • a[9] 390000 – 39FFFF 1 January 2001

  17. Basic Data Structures • Arrays • When accessing a[5] we are actually accessing the 6th element • Compiler computes • 300000 + 5 * 16 = 350000 • 300000 - starting address • 5 - the 6th element • 16 - size of 1 element (int) • The size of an array is determined • When it is defined and cannot be changed later 1 January 2001

  18. Basic Data Structures • Arrays • Accessing an Array • The declaration • int aValue0 = myArray[3]; • Assigns to aValue0 • The value stored in element of myArray[] • Indexed by 3 • The statement • myArray[7] = aValue1; • Assigns to the element of myArray[ ] • Indexed by 7 • The value of aValue1 1 January 2001

  19. Basic Data Structures • Arrays • Initializing an Array • The expression • int myArray[3]; • Declares an array of 3 elements • Does not set the elements to any particular value • Tells the compiler to allocate 6 bytes of storage on a 16 bit machine 1 January 2001

  20. Basic Data Structures • Arrays • Initializing an Array • To initialize an array we can….. • 1. Assign value to each element manually • 2. Specify values as part of declaration • Specify initializers as comma separated list of values • Enclosed in { } 1 January 2001

  21. Basic Data Structures • Arrays • Initializing an Array • For the declaration…...int myArray[3]; • Using manual initialization we can write….. • myArray[0] = 4; • myArray[1] = 5; • myArray[2] = 6; • When initializers are specified as part of declaration, it is not • necessary to specify dimension we write….. • int myArray[ ] = { 4, 5, 6 }; 1 January 2001

  22. Basic Data Structures • Arrays • Number of Elements in an Array • We can calculate the number of elements in an array by using • the sizeof operator • Number of elements in an array is given by sizeof(array) / sizeof(array[0]) 1 January 2001

  23. Basic Data Structures • Strings • In C and C++ textual data is managed using strings • A string is sequence of char integers with one additional • requirement • Last character must have a value of zero • In C a string is a null terminated array of chars • We call this a C-style string • We refer to strings as terminated by a null character • This null character is simply a char with a value of zero 1 January 2001

  24. Basic Data Structures • Strings • The following declaration creates array of characters • This is not a string….. • char greeting[5] = {'H', 'e', 'l', 'l', 'o'}; • The following declaration does create a C-style string • char hello[5 + 1] = {'H', 'e', 'l', 'l', 'o', '\0'}; 1 January 2001

  25. Basic Data Structures • Strings • We may use any of several equivalent initialization syntaxes • When we declare a string but, some are easier to read than others • char hello[6] = {'H', 'e', 'l', 'l', 'o', '\0'}; • char hello[6] = "Hello"; • char hello[] = "Hello"; 1 January 2001

  26. Basic Data Structures • Strings • Notice strings are arrays • Thus we can write... • cout << hello[1] << endl; • …and we’ll display e on the screen. 1 January 2001

  27. Basic Data Structures • Strings • Some Standard Operations • There are many standard string operations in the C / C++ • libraries • One function is strlen()whichreturns the length of the string • Executing this line of code will display 5 not 6 on the screen • strlen() only returns the number of data characters in the string • It does not count the terminating null cout << strlen(“hello”) << endl; 1 January 2001

  28. Basic Data Structures • Strings • Using Strings as Input • the code fragment the enter the same 3 numbers • We will see that the variables take on following values • a gets 4 as a character which is 52 as an integer • b gets 5 as a character which is 53 as an integer • c gets 5 as a character which is 53 as an integer • d gets 6 as a character which is 54 as an integer • e gets 7 as a character which is 55 as an integer • f gets 4 as a character which is 52 as an integer int x; int y; int z; cin >> x; cin >> y cin >> z • Let’s enter 45 56 74 • We will see that • x has value 45 • y has value 56 • z has value 74 1 January 2001

  29. Basic Data Structures • Strings • Using Strings as Input • Let’s change the code…. char a; char b; char c; char d; char e; char f; cin >> a; cin >> b; cin >> c; cin >> d; cin >> e; cin >> f; • Let’s enter the same 3 numbers…. • We will see that the variables take on following values • a gets 4 as a character which is 52 as an integer • b gets 5 as a character which is 53 as an integer • c gets 5 as a character which is 53 as an integer • d gets 6 as a character which is 54 as an integer • e gets 7 as a character which is 55 as an integer • f gets 4 as a character which is 52 as an integer 1 January 2001

  30. Basic Data Structures • Strings • Using Strings as Input • There was no way to get all of the data from the keyboard at • once • To do this • The cin object must be switched • From formatted input using the >> operator • To line-input • Now we must use thegetline() function • This function is part of the cin object 1 January 2001

  31. Basic Data Structures • Strings • Using Strings as Input • The following code fragment shows how we might use getline() • The dot after cin is known as the member-of operator • We use it to refer to a member of an object const int SIZE = 80; // Capitalize CONSTANTS char array[SIZE]; cin.getline(array, SIZE); cout << array << endl; 1 January 2001

  32. Basic Data Structures • Strings • Using Strings as Input • The getline() method is a function that takes as arguments • The name of an array in which to store data from the keyboard • The size of that array 1 January 2001

  33. Basic Data Structures • Strings • Using Strings as Input • If we use the code fragment above and enter • I think you’re just string me along… • cin.getline() will • If getline reads the newline character it will cease reading and • Insert a null into the array • Note: Only 79 characters are read 1. Read characters from the keyboard and 2. Put them in the array 3. Until it has put 79 characters in the array or It reads the newline character 1 January 2001

  34. Basic Data Structures • Strings • Mixing Formatted and Line Input • If we write a program that uses both >> operator and the • cin.getline()method to receive input from the keyboard • We can have problems keeping things straight • Specifically >> leaves the newline in the input buffer • If our next line of code uses cin.getline() • The newline character will be • Picked up immediately • Converted to a null character • Appended to the array • Our array now has a string with no characters in it 1 January 2001

  35. Basic Data Structures • Strings • Mixing Formatted and Line Input • To address the problem, we should use another method • cin.get() which can get a single character from the keyboard • Let’s use the following code fragment and enter Hello char data; cin.get(data); cout << data << endl; // displays H cin.get(data); cout << data << endl; // displays e 1 January 2001

  36. Basic Data Structures • Advanced Data Types - Unions and Structures • ADT • An Abstract Data Type specifies • Data type • Collection of operations on that data type • Operations specify access to data • The retrieval, modification, and internal implementation • of the data type are hidden from the programmer 1 January 2001

  37. Basic Data Structures • Advanced Data Types - Unions and Structures • A Point in rectangular co-ordinate system has x and y co-ordinates • Such a point can be represented as structure • struct Point • { • int x; • int y; • }; 1 January 2001

  38. Basic Data Structures • Advanced Data Types - Unions and Structures • Structure • Identified by keyword struct • Optional name • Structure tag which names the structure • Collection of variables called data members 1 January 2001

  39. Basic Data Structures • Advanced Data Types - Unions and Structures • Member Access • The members of a struct are referred to with construct of the form • structureName.member; • Given the declaration • Point pt; • Which declares pt to be a structure of type Point • We can access the x and y members as follows, • pt.x // refers to the x variable • pt.y // refers to the y variable 1 January 2001

  40. Basic Data Structures • Advanced Data Types - Unions and Structures • Initialization • A struct can be initialized in several ways • Like an array….. • We can following the declaration with a list of initializers • Point pt = {100, 200}; • There is a 1 - 1 correspondence between the initializer values • and the data members 1 January 2001

  41. Basic Data Structures • Advanced Data Types - Unions and Structures • Nesting • A structure can be nested inside another structure • Continuing our example, a rectangle is fully specified by its • opposite vertices • Thus…. • We can write • Specifies a structure of type Rectangle • Observe: • struct Rectangle • { • Point pt1; • Point pt2; • }; 1 January 2001

  42. Basic Data Structures • Advanced Data Types - Unions and Structures • Accessing Nested Members • Accessing member of nested struct is a simple extension of what • we’ve done so far • Given declaration: • struct Rectangle r1; • r1.pt1.x • Refers to x co-ordinate of pt1 • r1.pt1.y • Refers to y co-ordinate of pt1 • We can initialize r1 with a bracketed list of initializers • Rectangle r1 = {pt1, pt2}; • We cannot Initialize with bracket list of points • Rectangle r1 = {1, 3, 5, 7}; • We can initialize the points • Point tempPoint = {3, 4}; • Then assign the points to the Rectangle instance, r1 • r1.pt1 = tempPoint; 1 January 2001

  43. Basic Data Structures • Advanced Data Types - Unions and Structures • Operations • The only legal operations on a struct • Copying • Assignment to as a unit • Taking the address using & operator • Structs • Cannot be compared • Operations such as • Are illegal • struct Point{…}; • Point pt1, pt2; • if (pt1 == pt2) • { • stuff • } 1 January 2001

  44. Basic Data Structures • Advanced Data Types - Unions and Structures • Unions • Unions come to C++ from C and were heavily used when • computers had very little memory • When we declare an Instance of a struct….all members of the • struct are in memory at same time • A union works exactly like a struct except that only one member • can be in memory at a time • Thus union is variable that can hold objects of different • types and size at different times int float char char* 1 January 2001

  45. Basic Data Structures • Advanced Data Types - Unions and Structures • Unions • syntax • union name • { • type1 var1; • type2 var2; • . • . • typen varn; • } uVar; • name - union variable name • uVar - variable with multiple types • typei - any of the types • vari - variable of typei 1 January 2001

  46. Basic Data Structures • Advanced Data Types - Unions and Structures • Unions • At compile time • uVar is allocated sufficient memory to hold the largest typei • At run time • uVar may hold any of the specified types 1 January 2001

  47. Basic Data Structures • Advanced Data Types - Unions and Structures • Unions • If we declare • Then we declare an instance of the union • Mine myMine; • myMine • Allocated sufficient memory space to hold a float • Largest of the specified types • union Mine • { • int intValue; • float floatValue; • char charValue; • }; 1 January 2001

  48. Basic Data Structures • Advanced Data Types - Unions and Structures • Unions 1 January 2001

  49. Basic Data Structures • Advanced Data Types - Unions and Structures • Unions • Member Access • We access union member exactly like struct unionName.member unionPtr -> member 1 January 2001

  50. Basic Data Structures • Advanced Data Types - Unions and Structures • Unions • Initialization • A union can be initialized by aggregation • …but, only with value of type of first member 1 January 2001

More Related