1 / 37

Structured Data

Structured Data. Dr. Jose Annunziato. Abstract Data Types. Abstract Data Types (ADTs) are custom types that are defined in terms of other types, including primitive types and other ADTs ADTs define the data being operated on as well as the family of operations that manipulate the data

etenia
Download Presentation

Structured Data

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. Structured Data Dr. Jose Annunziato

  2. Abstract Data Types • Abstract Data Types (ADTs) are custom types that are defined in terms of other types, including primitive types and other ADTs • ADTs define the data being operated on as well as the family of operations that manipulate the data • C++ provides two mechanisms to define ADTs • Structures • Classes

  3. Structures • Use thestruct keyword to define a new data type struct Employee { string firstName; string lastName; int age; float salary; string hireDate; }

  4. Transaction ADT • We group the variables for our bank application into a structure struct Transaction { string date; int type; string description; float amount; } • Notice struct does not contain balance

  5. Declaring Variables of New Type • Declaring variables consists of declaring the type of the variable, and then the name of the variable • For structures it is no different. Declare a new variable with the new data type as its type • The size of memory needed to hold the new variable is the sum of the individual members of the structure Employee alice, bob, charlie; Transaction deposit1, deposit2, withdraw1;

  6. Struct Vs. Parallel Arrays • Structures are an improvement over the parallel array representation • Instead of having several arrays representing various records, a single record can be represented by a single structure instance withdraw1

  7. Accessing Structure Members • Once a variable has been declared to be of a type, the individual members can be accessed using the dot notation • This consist of using the "." in between the name of the variable and the name of the property • Parent / Child relation or "Has A" relation alice.firstName = "Alice"; alice.salary += 1000.0; deposit1.amount = 200.0; cout << bob.hireDate << endl;

  8. Comparing Structures • To compare structures, compare each of the elements Transaction t1, t2; booltransactionsEqual = false; if ( t1 == t2 ) transactionsEqual = true; // X if ( t1.date == t2.date && // OK t1.type == t2.type && t1.description == t2.description && t1.amount == t2.amount && t1.balance == t2.balance ) transactionsEqual = true;

  9. Initializing a Structure • Structures can be initialized when they are declared by providing all or some of the values for their members Employee charlie= { "Charlie", "Steel", 42, 75000, "9/1/2012" }; Transaction deposit2 = { "7/15/2012 11:22:33", 0, "wages", 2500.00 }; Transaction withdraw1 = { "…", 1, "…" }; • You can't skip initializations Employee bob = { "Robert", , 62, , };

  10. Arrays of Structures • Use arrays to handle various instances of structures of the same type • Arrays of structures are declared using the same syntax as for primitive data types Employee hourlyEmployee[10]; Employee salariedEmployee[100]; Transaction monthlyStatement[31]; Transaction yearEndStatement[365]; • Wouldn’t it be great to relate hourlyEmployees and salariedEmployees? Classes will allow this…later

  11. Nested Structures • Structures can group any other data types including other ADTs • For instance, instead of using string data type for dates, we can declare a data type that better represents the data structure Date { int month, day, year; int hour, minutes, seconds; } • ADTs allow thinking about problems at proper abstraction

  12. Declare Data Types as Members structure Employee { string hireDate; Date hireDate; … } structure Transaction { string date; Date date; … }

  13. Define Data Type Instance as Member • Define a data type instance and assign as a member Date hireDate = { 7 , 11, 2012, 4, 55, 34 }; Employee charlie = { …, hireDate, … }; Date depositDate= { 6, 10, 2012, 3, 4, 5 }; Transaction openAccount = { depositDate, … }; • You can change the structure after definition depositDate.day = 11; Transaction deposit2; deposit2.date = depositDate;

  14. Traversing Nested Types • Similar to using / or \ to navigate a directory path, use the dot (.) notation to navigate nested types struct Employee { Date lastRaise; float salary; } Employee charlie; charlie.salary += 1000.0; charlie.lastRaise.month = 7; charlie.lastRaise.day = 14; charlie.lastRaise.year = 2012;

  15. Traversing Nested Data Type Arrays struct Account { Transaction transactions[]; inttransactionCount; } Account checking; for ( int s = 0; s < checking.transactionCount; s++ ) { cout << checking.transactions[ s ].balance; }

  16. Use Ctime To Get Current Time • The ctime library already declares a time structure #include <ctime> … time_trawTime = time ( 0 ); structtm * timeInfo = localtime ( &rawTime ); Date hireDate = { timeInfo->tm_mon, timeInfo->tm_mday, timeInfo->tm_year };

  17. Passing Structures to Functions • Like regular variables, structure variables can be passed to functions by value or by reference • Passing by value copies the variable onto the parameter and the function can not change the original variable • Passing by reference does copy the variable and allows the function to act on the original variable • Use the & operator to pass by reference just like regular variables

  18. Giving Everyone a Raise void giveRaise (Employee &employee, float percent ); int main() { Employee alice; giveRaise ( alice, 7 ); Employee employees [ 2300 ]; for ( int e = 0; e < 2300; e++ ) giveRaise ( employee [ e ], 5 ); } void giveRaise (Employee&employee, float percent ) { employee.salary *= ( percent / 100.0 ) + 1; }

  19. Constant Structures • Even though a function does not change the parameter structure, you might want to pass it as reference anyway if the structure is too large • Declare parameters as const if they should not be changed by function void printEmployee ( const Employee &employee ) { cout << employee.firstName << " "; cout << employee.lastName << endl; … }

  20. Returning Structures from Functions • Functions can create structure instances; these are sometimes called factories Employee*employeeFactory ( string fName, string lName, float salary, Date hireDate ) { Employee* employee = new Employee; employee->firstName= fName; employee->lastName= lName; employee->hireDate= hireDate; employee->salary = salary; return employee; }

  21. Get Current Date #include <ctime> Date getCurrentDate() { time_trawTime = time ( 0 ); struct tm * timeInfo = localtime ( &rawTime ); Date dateNow = { timeInfo->tm_mon, timeInfo->tm_mday, timeInfo->tm_year, timeInfo->tm_hour, timeInfo->tm_min, timeInfo->tm_sec }; return dateNow; }

  22. Transaction Factory • Factories hide details for creating instances Transaction createTransaction( int type, float amount, string description ) { Transaction tx; tx.date = getCurrentDate(); tx.type = type; tx.description = description; tx.amount = amount; return tx; }

  23. Enumerated Data Types • Enumerated data types define enumerators, named values that represent sequential integer values • Enumerations are a better alternative to constant integers and improve type checking • Useful for defining a group of related integer values • Use enum keyword to define enumerations enumTransactionType { DEPOSIT, WITHDRAW, TRANSFER }; TransactionType type1 = DEPOSIT;

  24. Enumerators Must Be Unique • Enumerators belong to the same name space enum Presidents { MCKINLEY, ROOSEVELT, TAFT }; enum VPs { ROOSEVELT, FAIRBANKS, SHERMAN }; • You can not re-declare the enumerator even if it has the same value; enum Status { ON, OFF }; int OFF = 1;

  25. Enumerators are Integers • By default enumerators are assigned values 0, 1, 2… • You can print the enumerators and they will print their integer equivalent cout << DEPOSIT << endl; cout << WITHDRAW << endl; cout << TRANSFER << endl;

  26. Overriding Enum Integer Values • When you declare enum data types, you can specify the integer values of the enumerators enum Water { FREEZING = 0, BOLING = 100 }; • You can not change the values of the enumerators after they are declared

  27. Enumerating Transactions • Instead of using constants or named integers, enums allow compilers to catch potential bugs struct Transaction { string date; int type; } enumTransactionType { DEPOSIT, WITHDRAW }; struct Transaction { Datedate; TransactionType type; }

  28. Enumerating Transactions • Instead of using constants or named integers, enums allow compilers to catch potential bugs const int DEPOSIT = 0; // use enum instead const int WITHDRAW = 1; enumTransactionType { DEPOSIT, WITHDRAW }; … Transaction deposit = { …, DEPOSIT, … } Transaction withdraw; withdraw.type = WITHDRAW;

  29. Can't Assigning Values to Enums • You can not assign integer values to enumerators DEPOSIT = 45; // X • It's a good thing since we don’t want to accidentally assign a bad integer to an enum type Transaction withdraw; withdraw.type = 0; // X • We want to avoid mistakes such as Transaction withdraw; withdraw.type = 21; // X

  30. Assigning Enumerators to int Variables • Although you can not write to an enum, you can read it and use it as an integer enum Day = { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY }; int x = THURSDAY; cout << x << endl; Day workDay = FRIDAY; int y = workDay; cout << y << endl;

  31. Comparing Enumerator Values • Since enums can be read as integers, they can be compared as such if ( FRIDAY > MONDAY ) cout << "Friday comes after Monday" << endl; if ( MONDAY == 0 ) cout << "Monday is the first day" << endl;

  32. Iterating Over Enums • You can use enumerators as array indices or as loop sentinels float dailyBalances[ 7 ]; dailyBalances [ MONDAY ] = 100.0; dailyBalances [ TUESDAY ] = 100.0; … dailyBalances [ SUNDAY ] = 1234.0; for ( int day = MONDAY; day < FRIDAY; day++ ) { cout << dailyBalances [ day ] << endl; }

  33. Anonymous Enumerated Types • If you don’t need to declare variables with the enum data type, there is no need to name the new type • Use enum just to create the enumerators enumDay{ MONDAY, TUESDAY, …, FRIDAY }; • Here it is as an anonymous enumeration enum { MONDAY, TUESDAY, …, FRIDAY };

  34. Changing Enums with Math • Remember that you can not change the value of an enumerator • If an enumerator is used in an arithmetic expression, the result is not an enumerator and therefore it can not be assigned to an enum Day day1, day2; day1 = TUESDAY; day2 = day1 + 1; // X

  35. Using Enums in Switch Case • A common use of enums is in switch statements to choose among various actions Day today; switch ( today ) { case MONDAY : case TUESDAY : … case FRIDAY : cout << "TGIF" << endl; break … }

  36. Declaring Enums and Variables Together • When declaring enumerations you can declare variables as well • Instead of using 2 lines: enumTransactionType { DEPOSIT, WITHDRAW }; TransactionType type1; • You can use 1 line: enumTransactionType { … } type1;

  37. StructureDemo.cpp • StructureDemo.cpp • StructureDemoLibrary.h • StructureDemoLibrary.cpp

More Related