View
216
Download
1
Embed Size (px)
Citation preview
1104/18/2304/18/23 21:1621:16 Arrays and StructuresArrays and Structures
Arrays and StructuresArrays and Structures
Methods to manipulate a collection of Methods to manipulate a collection of values under one name.values under one name.Arrays:Arrays: Homogenous dataHomogenous data Variable quantity of data items all of the same Variable quantity of data items all of the same
typetype
Structures:Structures: Heterogeneous dataHeterogeneous data Fixed quantity of data values of different typesFixed quantity of data values of different types
2204/18/2304/18/23 21:1621:16 Arrays and StructuresArrays and Structures
ArraysArrays
Declaration:Declaration:
<data-type> <var-name>[int-qty]<data-type> <var-name>[int-qty]
Access:Access:
<var-name>[subscript]<var-name>[subscript]
Subscript:Subscript: IntegerInteger In the range 0 to n-1, where n is the number In the range 0 to n-1, where n is the number
of elementsof elements
3304/18/2304/18/23 21:1621:16 Arrays and StructuresArrays and Structures
StructuresStructures
Definition:Definition:struct <struct-name> // typically in global areastruct <struct-name> // typically in global area{{
<elements>…. /* composed of data types <elements>…. /* composed of data types and element names */and element names */
};};Declaration:Declaration:<struct-name> <var-name><struct-name> <var-name>Access:Access:<var-name>.<element-expression><var-name>.<element-expression>
4404/18/2304/18/23 21:1621:16 Arrays and StructuresArrays and Structures
Array ExamplesArray Examples
* int counts[100]; … counts[0] = 0;* int counts[100]; … counts[0] = 0;
double speeds[2000]; … speeds[1999] = double speeds[2000]; … speeds[1999] = 1.23;1.23;
string names[500]; … cout << “Name: “ << string names[500]; … cout << “Name: “ << names[10];names[10];
5504/18/2304/18/23 21:1621:16 Arrays and StructuresArrays and Structures
Structures ExampleStructures Example
Structures:Structures: struct employeestruct employee
{{string name;string name;float annual_salary;float annual_salary;int dept_num;int dept_num;
};}; employee boss;employee boss; boss.name = “Bill”;boss.name = “Bill”; cout << “Annual Salary is “ << boss.annual_salary << cout << “Annual Salary is “ << boss.annual_salary <<
“\n”;“\n”;
6604/18/2304/18/23 21:1621:16 Arrays and StructuresArrays and Structures
NestingNesting
An array may be an array of arrays or an An array may be an array of arrays or an array of structures.array of structures.
A structure may have arrays as members A structure may have arrays as members or other structures as members.or other structures as members.
These arrays or structures may also have These arrays or structures may also have arrays or structures as members, and so arrays or structures as members, and so forth to any arbitrary depth.forth to any arbitrary depth.
7704/18/2304/18/23 21:1621:16 Arrays and StructuresArrays and Structures
Nesting ExampleNesting Example
struct classstruct class{{
string time;string time;string place;string place;string students[30]; // structure w/ arraystring students[30]; // structure w/ array
};};class schedule[5]; // array of structuresclass schedule[5]; // array of structuresschedule[0].place = “Robinson 310”;schedule[0].place = “Robinson 310”;schedule[0].students[0] = “Bill”;schedule[0].students[0] = “Bill”;
8804/18/2304/18/23 21:1621:16 Arrays and StructuresArrays and Structures
Arrays and For LoopsArrays and For Loops
For loops are typically used to process For loops are typically used to process arrays.arrays.Typically when using arrays, the number Typically when using arrays, the number of elements that actually contain valid data of elements that actually contain valid data is saved in a variable.is saved in a variable.for (i=0; i<NUM_ELEMENTS; ++i)for (i=0; i<NUM_ELEMENTS; ++i)
counts[i] = 0;counts[i] = 0;
for (i=0; i<n; ++i)for (i=0; i<n; ++i)area[i] = base[i] * height[i];area[i] = base[i] * height[i];
9904/18/2304/18/23 21:1621:16 Arrays and StructuresArrays and Structures
SentinalsSentinals
int SENTINEL = -1;int SENTINEL = -1;
Sentinels may also be used:Sentinels may also be used:i = 0;i = 0;
while (speeds[i] != SENTINEL)while (speeds[i] != SENTINEL)
cout << speed[i] << “\n”;cout << speed[i] << “\n”;
++ i;++ i;
}}
101004/18/2304/18/23 21:1621:16 Arrays and StructuresArrays and Structures
TerminologyTerminology
Scalars: a single data valueScalars: a single data value
Vectors: a one-dimensional arrayVectors: a one-dimensional array
Matrices: a two-dimensional arrayMatrices: a two-dimensional array
111104/18/2304/18/23 21:1621:16 Arrays and StructuresArrays and Structures
StringsStrings
A string is a array of characters.A string is a array of characters.A string literal is delimited by double-quotation A string literal is delimited by double-quotation marks.marks.Examples:Examples: ““Computer”Computer” ““special characters in it: !@#$\”\\ ”special characters in it: !@#$\”\\ ” ““one”one” ““1”1” “”“” NOT strings: ‘a’, ‘1’, 1, oneNOT strings: ‘a’, ‘1’, 1, one
121204/18/2304/18/23 21:1621:16 Arrays and StructuresArrays and Structures
Another method to do inputAnother method to do input
getline(cin, a_string, ‘\n’);getline(cin, a_string, ‘\n’);This will accept all input up to a newline This will accept all input up to a newline
character. It will store the input (NOT the character. It will store the input (NOT the newline) in a_string.newline) in a_string.
There are functions to do character-at-a-There are functions to do character-at-a-time input, as well as other special input time input, as well as other special input functions (see lecture on streams and functions (see lecture on streams and files).files).In practice, these functions sometimes do In practice, these functions sometimes do not mix well with cin, with erratic results.not mix well with cin, with erratic results.
131304/18/2304/18/23 21:1621:16 Arrays and StructuresArrays and Structures
Using Strings in C++Using Strings in C++
#include <string>#include <string>Declaring strings:Declaring strings: string name;string name; string account_number;string account_number;
Using strings:Using strings: Name = “Bob”;Name = “Bob”; cin >> account_number;cin >> account_number; whole_name = last_name + “, “ + first_name; // whole_name = last_name + “, “ + first_name; //
ConcatenationConcatenation Name_length = name.length();Name_length = name.length();
141404/18/2304/18/23 21:1621:16 Arrays and StructuresArrays and Structures
PointersPointers
A pointer is a variable that contains the A pointer is a variable that contains the address of another variable, that is, a address of another variable, that is, a memory address.memory address.
Definition: <data-type> * <var-name>Definition: <data-type> * <var-name>
Access: <var-name> for the pointer itself; Access: <var-name> for the pointer itself; *<var-name> for the variable pointed to *<var-name> for the variable pointed to (“de-referencing”).(“de-referencing”).
151504/18/2304/18/23 21:1621:16 Arrays and StructuresArrays and Structures
Dynamic MemoryDynamic Memory
Three areas of memory:Three areas of memory: Global: defined outside any function (allocated once)Global: defined outside any function (allocated once) Local: defined inside a function (allocated on the Local: defined inside a function (allocated on the
system stack)system stack) Dynamic (also known as the heap)Dynamic (also known as the heap)
Accessed through operators new and deleteAccessed through operators new and delete
To request a section of memory: To request a section of memory:
<pntr-var> = new <data-type><pntr-var> = new <data-type>
To access that memory: use operators [], *, ->To access that memory: use operators [], *, ->
To return that memory: delete <pntr-var>To return that memory: delete <pntr-var>
161604/18/2304/18/23 21:1621:16 Arrays and StructuresArrays and Structures
Memory ExamplesMemory Examples
#include <iostream>#include <iostream>using namespace std;using namespace std;int g; // global: visible from here to end of fileint g; // global: visible from here to end of filevoid main()void main(){{
float l; // local: visible from here to end of blockfloat l; // local: visible from here to end of blockdouble* h = new double; // heap allocationdouble* h = new double; // heap allocationdelete h; // heap de-allocationdelete h; // heap de-allocationint* weights = new int[num_weights]; // delete[]int* weights = new int[num_weights]; // delete[]
}}
171704/18/2304/18/23 21:1621:16 Arrays and StructuresArrays and Structures
ReadingReading
Chapter 9Chapter 9
Chapter 11, Section 1-2Chapter 11, Section 1-2
Chapter 13, Sections 1-2Chapter 13, Sections 1-2