structured data

Post on 16-Feb-2016

64 Views

Category:

Documents

0 Downloads

Preview:

Click to see full reader

DESCRIPTION

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 - PowerPoint PPT Presentation

TRANSCRIPT

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

• C++ provides two mechanisms to define ADTs– Structures– Classes

Structures• Use the struct keyword to define a new data type

struct Employee {string firstName;string lastName;int age;float salary;string hireDate;

}

Transaction ADT• We group the variables for our bank application into

a structurestruct Transaction {

string date;int type;string description;float amount;

}

• Notice struct does not contain balance

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;

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

date[] type[] description[] amount[] balance[]

7/11/12 DEPOSIT Open Account 1000.0 1000.0

7/12/12 WITHDRAW Groceries 123.45 876.55

7/13/12 DEPOSIT Wages 2578.0 3454.55

7/14/12 WITHDRAW Pharmacy 34.56 3419.99

withdraw1

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;

Comparing Structures• To compare structures, compare each of the

elementsTransaction t1, t2;bool transactionsEqual = false;if ( t1 == t2 ) transactionsEqual = true; // Xif ( t1.date == t2.date && // OKt1.type == t2.type &&t1.description == t2.description &&t1.amount == t2.amount &&t1.balance == t2.balance )transactionsEqual = true;

Initializing a Structure• Structures can be initialized when they are declared

by providing all or some of the values for their membersEmployee 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 initializationsEmployee bob = { "Robert", , 62, , };

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 typesEmployee 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

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 datastructure Date {

int month, day, year;int hour, minutes, seconds;

}• ADTs allow thinking about problems at proper

abstraction

Declare Data Types as Membersstructure Employee {string hireDate;Date hireDate;…}

structure Transaction {string date;Date date;…}

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 definitiondepositDate.day = 11;Transaction deposit2;deposit2.date = depositDate;

Traversing Nested Types• Similar to using / or \ to navigate a directory path, use

the dot (.) notation to navigate nested typesstruct Employee {Date lastRaise;float salary;}Employee charlie;charlie.salary += 1000.0;charlie.lastRaise.month = 7;charlie.lastRaise.day = 14;charlie.lastRaise.year = 2012;

Traversing Nested Data Type Arrays

struct Account {Transaction transactions[];int transactionCount;

}Account checking;for ( int s = 0; s < checking.transactionCount; s++ ) {

cout << checking.transactions[ s ].balance;}

Use Ctime To Get Current Time• The ctime library already declares a time structure

#include <ctime>…time_t rawTime = time ( 0 );struct tm * timeInfo = localtime ( &rawTime );

Date hireDate = {timeInfo->tm_mon,timeInfo->tm_mday,timeInfo->tm_year};

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

Giving Everyone a Raisevoid 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;}

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;…}

Returning Structures from Functions• Functions can create structure instances; these are

sometimes called factoriesEmployee* 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;}

Get Current Date#include <ctime>Date getCurrentDate() {time_t rawTime = 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;}

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;

}

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

enum TransactionType { DEPOSIT, WITHDRAW, TRANSFER };

TransactionType type1 = DEPOSIT;

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;

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;

Overriding Enum Integer Values• When you declare enum data types, you can specify

the integer values of the enumeratorsenum Water { FREEZING = 0, BOLING = 100 };

• You can not change the values of the enumerators after they are declared

Enumerating Transactions• Instead of using constants or named integers, enums

allow compilers to catch potential bugsstruct Transaction {string date;int type;}enum TransactionType { DEPOSIT, WITHDRAW };struct Transaction {Date date;TransactionType type;}

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;enum TransactionType { DEPOSIT, WITHDRAW };…Transaction deposit = { …, DEPOSIT, … }Transaction withdraw;withdraw.type = WITHDRAW;

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 typeTransaction withdraw;withdraw.type = 0; // X

• We want to avoid mistakes such asTransaction withdraw;withdraw.type = 21; // X

Assigning Enumerators to int Variables• Although you can not write to an enum, you can read

it and use it as an integerenum Day = { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY };

int x = THURSDAY;cout << x << endl;

Day workDay = FRIDAY;int y = workDay;cout << y << endl;

Comparing Enumerator Values• Since enums can be read as integers, they can be

compared as suchif ( FRIDAY > MONDAY )

cout << "Friday comes after Monday" << endl;

if ( MONDAY == 0 )cout << "Monday is the first day" << endl;

Iterating Over Enums• You can use enumerators as array indices or as loop

sentinelsfloat 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;}

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 enumeratorsenum Day { MONDAY, TUESDAY, …, FRIDAY };

• Here it is as an anonymous enumerationenum { MONDAY, TUESDAY, …, FRIDAY };

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 enumDay day1, day2;day1 = TUESDAY;day2 = day1 + 1;// X

Using Enums in Switch Case• A common use of enums is in switch statements to

choose among various actionsDay today;switch ( today ) {

case MONDAY :case TUESDAY :…case FRIDAY : cout << "TGIF" << endl; break…

}

Declaring Enums and Variables Together• When declaring enumerations you can declare

variables as well• Instead of using 2 lines:

enum TransactionType { DEPOSIT, WITHDRAW };TransactionType type1;

• You can use 1 line:enum TransactionType { … } type1;

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

top related