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;