Arrays Flashcards

1
Q

Array

A

Variable that can store multiple values of the same type

Values are stored in adjacent memory locations

Declared using [ ] operator

Int test [5];

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

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

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

An element is accessed with

A
the at() function
vector yearsList(4);

yearsList.at(0) = 1999;

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

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

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Declare a vector named myVals that stores 10 items of type int.

A

vector myVals(10);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Assign tempVal with the myVals’ element at the index one after the value held in variable i.

A

tempVal = myVals.at(i + 1);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

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:

A
// 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).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

True/False: To find the maximum element value, a reasonable statement preceding the for loop is: int maxVal = 0;

A

False: 0 would yield a wrong final maxVal if all element values were negative. A better statement would be: maxVal = myVctr.at(0).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Range-based for loop

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

5.5.1: The range-based for loop declares a new variable and assigns the variable with each successive element of a container.

A

vector teamRoster;

// Adding player names
teamRoster.push_back(“Mike”);
teamRoster.push_back(“Scottie”);
teamRoster.push_back(“Toni”);

cout &laquo_space;“Current roster: “ &laquo_space;endl;

for (string playerName : teamRoster) {
cout &laquo_space;playerName &laquo_space;endl;
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Compared to a regular for loop, a range-based for loop

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

Modifying vector using range-based for loop

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

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.

A
#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 &laquo_space;intVal &laquo_space;endl;
}

13
19
17
14
11
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

Range-based for loop with auto

A

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) {

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

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

A

using resize(N). Ex: highScore.resize(10) resizes the highScores vector to have 10 elements.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

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);

A

would delete element 2, leaving elements 0 and 1. A subsequent access to userScores.at(2) would result in an error.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

Appending items to a vector

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

Table 5.8.1: Functions on the back of a vector.

push_back()

back()

pop_back()

A
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.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

Element by element vector copy

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

Figure 5.11.4: Vector reversal program with correct output.

A
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 &laquo_space;“Enter “ &laquo_space;NUM_ELEMENTS &laquo_space;” integer values…” &laquo_space;endl;
for (i = 0; i < revVctr.size(); ++i) {
cout &laquo_space;“Value: “;
cin&raquo_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;
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

C++ supports two kinds of ordered list types.

A

Arrays: declared as int myList[10], accessed as myList[i].
Vectors: declared as vector myList(10), accessed as myList.at(i).

22
Q

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

A

as row-major order.

23
Q

Char arrays were the only kinds of strings in C++’s predecessor language C, and thus are sometimes called

A

C strings to distinguish them from C++’s string type.

24
Q

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

A

null character, written as ‘\0’. Given a string literal like “Star Wars”, the compiler automatically appends a null character.

25
Q

If a char array is initialized when declared, then the char array’s size may be omitted, as in char userName[] = “Hellen”;

A

The compiler determines the size from the string literal, in this case 6 + 1 (for the null character), or 7.

26
Q

An array of characters ending with a null character is known as a

A

null-terminated string.

27
Q

An individual array element can be processed like any other type of C++ variable.

A

True

28
Q

In C++11 the range-based for loop is best used in situations where you need the element subscript for some purpose.

A

False

29
Q

A vector object automatically expands in size to accommodate the items stored in it.

A

True

30
Q

By using the same ________ you can build relationships between data stored in two or more arrays.

A

subscript

31
Q

The name of an array stores the ________ of the first array element.

A

memory address

32
Q

An array can store a group of values, but the values must be

A

the same data type

33
Q

An array’s size declarator must be a ________ with a value greater than ________.

A

constant integer expression, zero

34
Q

Subscript numbering in C++

A

begins with zero

35
Q

Arrays must be ________ at the time they are ________.

A

initialized, declared

36
Q

An array can easily be stepped through by using a

A

a for loop

37
Q

The range-based for loop in C++11 is designed to work with a built-in variable known as

A

the range variable

38
Q

It is ________ to pass an argument to a function that contains an individual array element, such as scores[3].

A

legal in C++

39
Q

The ________ is automatically appended to a character array when it is initialized with a string constant.

A

null terminator

40
Q

When writing functions that accept multi-dimensional arrays as arguments, ________ must be explicitly stated in the parameter list.

A

all but the first dimension

41
Q

This vector function returns true if the vector has no elements.

A

empty

42
Q

A vector is an

A

ordered list of items of a given data type.

43
Q

Each item in a vector is called

A

an element.

44
Q

A programmer must include the statement

A

include at the top of the file when planning to use vectors.

45
Q

In a vector access, the number in .at() parentheses

A

is called the index of the corresponding element. The first vector element is at index 0.

46
Q

A vector’s elements are automatically initialized to

A

0s during the vector declaration.

47
Q

All of a vector’s elements may be initialized to another single value. Ex: vector myVector(3, -1); creates a vector named myVector with

A

three elements, each with value -1.

48
Q

A programmer may initialize each vector element with different values by specifying the initial values in braces {} separated by

A

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.

49
Q

Common for loop structure for iterating through a vector.

A
// Iterating through myVector
for (i = 0; i < myVector.size(); ++i) {
   // Loop body accessing myVector.at(i)
}
50
Q

Accessing an index that is out of range causes the program to automatically abort execution, typically with an error message being automatically printed.

A

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

51
Q

To find the maximum element value, a reasonable statement preceding the for loop is: int maxVal = 0;

A

False:

0 would yield a wrong final maxVal if all element values were negative. A better statement would be: maxVal = myVctr.at(0).