Arrays Flashcards
Array
Variable that can store multiple values of the same type
Values are stored in adjacent memory locations
Declared using [ ] operator
Int test [5];
A programmer commonly needs to maintain a list of items, just as people often maintain lists of items like a grocery list or a course roster. A
vector is an ordered list of items of a given data type. Each item in a vector is called an element. A programmer must include the statement #include at the top of the file when planning to use vectors. vector declaration: vector vectorName(numElements)
The statement above declares a vector with the specified number of elements, each element of the specified data type. The type of each vector element is specified within the angle brackets (<>). The number of vector elements is specified within parentheses following the vector name. Ex: vector gameScores(4); declares a vector gameScores with 4 integer elements.
Terminology note: { } are braces. < > are angle brackets, or chevrons. In a vector access, the number in .at() parentheses is called the index of the corresponding element. The first vector element is at index 0.
If you have studied arrays, then know that a vector was added to C++ as a safer and more powerful form of arrays, discussed elsewhere.
An element is accessed with
the at() function vector yearsList(4);
yearsList.at(0) = 1999;
A powerful aspect of vectors is that the index is an expression. Ex: userNums.at(i) uses the value held in the int variable i as the index. As such, a vector is useful to easily lookup the Nth item in a list.
A vector’s index must be an unsigned integer type. The vector index cannot be a floating-point type, even if the value is 0.0, 1.0, etc.
The program below allows a user to print the age of the Nth oldest known person to have ever lived. The program quickly accesses the Nth oldest person’s age using oldestPeople.at(nthPerson - 1). Note that the index is nthPerson - 1 rather than just nthPerson because a vector’s indices start at 0, so the 1st age is at index 0, the 2nd at index 1, etc.
Declare a vector named myVals that stores 10 items of type int.
vector myVals(10);
Assign tempVal with the myVals’ element at the index one after the value held in variable i.
tempVal = myVals.at(i + 1);
Iterating through vectors using loops is commonplace and is an important programming skill to master. Because vector indices are numbered 0 to N - 1 rather than 1 to N, programmers commonly use this for loop structure:
// Iterating through myVector for (i = 0; i < myVector.size(); ++i) { // Loop body accessing myVector.at(i
Note that index variable i is initialized to 0, and the loop expression is i < myVector.size() rather than i <= myVector.size(). If myVector.size() were 5, the loop’s iterations would set i to 0, 1, 2, 3, and 4, for a total of 5 iterations. The benefit of the loop structure is that each vector element is accessed as myVector.at(i) rather than the more complex myVector.at(i - 1).
True/False: To find the maximum element value, a reasonable statement preceding the for loop is: int maxVal = 0;
False: 0 would yield a wrong final maxVal if all element values were negative. A better statement would be: maxVal = myVctr.at(0).
Range-based for loop
The range-based for loop is a for loop that iterates through each element in a vector or container. A range-based for loop is also known as a for each loop. The range-based loop declares a new variable that will be assigned with each successive element of a container, such as a vector, from the first element to the last element.
5.5.1: The range-based for loop declares a new variable and assigns the variable with each successive element of a container.
vector teamRoster;
// Adding player names
teamRoster.push_back(“Mike”);
teamRoster.push_back(“Scottie”);
teamRoster.push_back(“Toni”);
cout «_space;“Current roster: “ «_space;endl;
for (string playerName : teamRoster) {
cout «_space;playerName «_space;endl;
}
Compared to a regular for loop, a range-based for loop
decreases the amount of code needed to iterate through containers, thus enhancing code readability and clearly demonstrating the loop’s purpose. A range-based for loop also prevents a programmer from writing code that incorrectly accesses elements outside of the container’s range.
Modifying vector using range-based for loop
To modify a vector’s elements using a range-based for loop, a programmer must declare the for loop’s variable as a reference. The reference variable will refer to each vector element as the for loop iterates through the vector elements. Assigning the reference variable with a new value assigns the corresponding vector’s element with that value. In the code example below, gradeVal will refer to each vector element, so the statement gradeVal = userGrade; assigns the vector elements with userGrade.
Correct for (int &currVal : intValues) starts a range-based for loop that declares a new reference variable &currVal that will refer to each element of the vector intValues. The body of the first loop adds 10 to currVal, which assigns intValues’s corresponding element with that value. The second loop prints out each element of intValues, which has been modified by the first loop.
#include #include using namespace std;
int main() { vector intValues; intValues.push_back(3); intValues.push_back(9); intValues.push_back(7); intValues.push_back(4); intValues.push_back(1);
for (int &currVal : intValues) {
currVal += 10;
}
for (int intVal : intValues) {
cout «_space;intVal «_space;endl;
}
13 19 17 14 11
Range-based for loop with auto
Programmers commonly use the auto type specifier to declare a range-based for loop’s variable. In the code example below, the compiler determines gradeVal is of type double because the elements of the vector examGrades are of type double.
for (auto gradeVal : examGrades) {
Commonly, the size of a list of items is not known during a program’s compile time. Thus, a vector’s size need not be specified in the vector’s declaration. Instead, a vector’s size can be set or changed while a program executes
using resize(N). Ex: highScore.resize(10) resizes the highScores vector to have 10 elements.
resize() can be called multiple times. If the new size is larger, resize() adds elements at the end. If smaller, resize() deletes elements from the end. If userScores has size 3 (elements 0, 1, 2), userScores.resize(2);
would delete element 2, leaving elements 0 and 1. A subsequent access to userScores.at(2) would result in an error.
Appending items to a vector
A programmer can append a new element to the end of an existing vector using a vector’s push_back() function. Ex: dailySales.push_back(521) creates a new element at the end of the vector dailySales and assigns that element with the value 521
Table 5.8.1: Functions on the back of a vector.
push_back()
back()
pop_back()
void push_back(const int newVal); Append new element having value newVal.
int back(); Returns vector's last element. Vector is unchanged.
void pop_back(); Removes the last element.
Element by element vector copy
In C++, the = operator conveniently performs an element-by-element copy of a vector, called a vector copy operation. The operation vectorB = vectorA resizes vectorB to vectorA’s size, appending or deleting elements as needed. vectorB commonly has a size of 0 before the operation.
Figure 5.11.4: Vector reversal program with correct output.
int main() { const int NUM_ELEMENTS = 8; // Number of elements vector revVctr(NUM_ELEMENTS); // User values unsigned int i; // Loop index int tmpValue; // Placeholder
cout «_space;“Enter “ «_space;NUM_ELEMENTS «_space;” integer values…” «_space;endl;
for (i = 0; i < revVctr.size(); ++i) {
cout «_space;“Value: “;
cin»_space; revVctr.at(i);
}
// Reverse
for (i = 0; i < (revVctr.size() / 2); ++i) {
tmpValue = revVctr.at(i); // These 3 statements swap
revVctr.at(i) = revVctr.at(revVctr.size() - 1 - i);
revVctr.at(revVctr.size() - 1 - i) = tmpValue;
}
// Print values cout << endl << "New values: "; for (i = 0; i < revVctr.size(); ++i) { cout << " " << revVctr.at(i); } cout << endl;
C++ supports two kinds of ordered list types.
Arrays: declared as int myList[10], accessed as myList[i].
Vectors: declared as vector myList(10), accessed as myList.at(i).
Conceptually, a two-dimensional array is a table with rows and columns. The compiler maps two-dimensional array elements to one-dimensional memory, each row following the previous row, known
as row-major order.
Char arrays were the only kinds of strings in C++’s predecessor language C, and thus are sometimes called
C strings to distinguish them from C++’s string type.
Because a string can be shorter than the character array, a string in a char array must end with a special character known as a
null character, written as ‘\0’. Given a string literal like “Star Wars”, the compiler automatically appends a null character.
If a char array is initialized when declared, then the char array’s size may be omitted, as in char userName[] = “Hellen”;
The compiler determines the size from the string literal, in this case 6 + 1 (for the null character), or 7.
An array of characters ending with a null character is known as a
null-terminated string.
An individual array element can be processed like any other type of C++ variable.
True
In C++11 the range-based for loop is best used in situations where you need the element subscript for some purpose.
False
A vector object automatically expands in size to accommodate the items stored in it.
True
By using the same ________ you can build relationships between data stored in two or more arrays.
subscript
The name of an array stores the ________ of the first array element.
memory address
An array can store a group of values, but the values must be
the same data type
An array’s size declarator must be a ________ with a value greater than ________.
constant integer expression, zero
Subscript numbering in C++
begins with zero
Arrays must be ________ at the time they are ________.
initialized, declared
An array can easily be stepped through by using a
a for loop
The range-based for loop in C++11 is designed to work with a built-in variable known as
the range variable
It is ________ to pass an argument to a function that contains an individual array element, such as scores[3].
legal in C++
The ________ is automatically appended to a character array when it is initialized with a string constant.
null terminator
When writing functions that accept multi-dimensional arrays as arguments, ________ must be explicitly stated in the parameter list.
all but the first dimension
This vector function returns true if the vector has no elements.
empty
A vector is an
ordered list of items of a given data type.
Each item in a vector is called
an element.
A programmer must include the statement
include at the top of the file when planning to use vectors.
In a vector access, the number in .at() parentheses
is called the index of the corresponding element. The first vector element is at index 0.
A vector’s elements are automatically initialized to
0s during the vector declaration.
All of a vector’s elements may be initialized to another single value. Ex: vector myVector(3, -1); creates a vector named myVector with
three elements, each with value -1.
A programmer may initialize each vector element with different values by specifying the initial values in braces {} separated by
commas.
Ex: vector carSales = {5, 7, 11}; creates a vector of three integer elements initialized with values 5, 7, and 11.
Such vector declaration and initialization does not require specifying the vector size, because the vector’s size is automatically set to the number of elements within the braces.
For a larger vector, initialization may be done by first declaring the vector, and then using a loop to assign vector elements.
Common for loop structure for iterating through a vector.
// Iterating through myVector for (i = 0; i < myVector.size(); ++i) { // Loop body accessing myVector.at(i) }
Accessing an index that is out of range causes the program to automatically abort execution, typically with an error message being automatically printed.
For example, for the declaration vector highScores(8), accessing highScores.at(8), or highScores.at(i) where i is 8, yields the following error message when running the program compiled with g++:
terminate called after throwing an instance of ‘std::out_of_range’
what(): vector::_M_range_check
Abort
DJ - Should be at(7) to account for the (-1) due to index beginning at 0
To find the maximum element value, a reasonable statement preceding the for loop is: int maxVal = 0;
False:
0 would yield a wrong final maxVal if all element values were negative. A better statement would be: maxVal = myVctr.at(0).