Chapter 4: Arrays, Dynamic Arrays, and Vectors Flashcards
Given the following code, what are the legal indexes for the array named “arr”.
int arr[4] = {2, 4, 6, 8, 10 };
0, 1, 2, 3, 4
Which of the following correctly initializes an array of int type named “arr” to contain four elements: 1, 2, 3, and 4.
I: int arr[4] = { 1, 2, 3, 4 };
II: int arr[4]; arr[1]=1; arr[2]=2; arr[3]=3; arr[4]=4;
III: int arr[4]; for (int i=0; i<4; i++) { arr[i]=i; }
IV: int arr[4]; int i=0 while(i<4) { arr[i]=i+1; i++; }
I and IV
Given the following code, what is the maximum number of elements to be populated to the “arr” array?
for (int i=0; i<n; i++)
{
arr[i] = i+1;
}
n
Given the following 2D array, the value of x[2][2] is __.
int x[3][4] = {{0,1,2,3}, {4,5,6,7}, {8,9,10,11}};
10
Which can find the size of an array named “arr” and then assign the value to a variable named “size”?
int size = sizeof(arr) / sizeof(arr[0])
Given the following code, which can deallocate the memory of “arr”?
int *arr = new int[5];
delete [] arr;
Given the following code, which can create an array of int type which can have up to 5 elements?
int size = 5;
int *a = new int[size];
Which is the advantage(s) of Vectors compared to arrays in C++?
I. Vectors do not have to declare size
II. Vectors can report their size and capacity
III. Vectors can grow in size
IV. Vectors do not take memory space
I, II, and III
Which declares a vector named “v” of 5 integers in C++?
vector<int> v (5);</int>
Which statement is correct about the “push_back()” function?
It adds a new element at the end.
What is an array in C++?
A fixed-size collection of elements of the same data type.
What can declare a dynamic array of integers named data with an initial size of 10?
int* data = new int[10];
By using new int[n] to create a dynamic array , what is the valid range of indices (indexes) you can use to access elements without causing undefined behavior?
0 to n-1
How is an array index typically defined?
A non-negative integer starting from 0.
What happens if you try to access an array element with an index that is out of bounds?
Undefined behavior, which can lead to crashes or incorrect results.
How do you declare an array of 10 integers named “numbers” in C++?
int numbers[10];
Which can deallocate the memory allocated to a dynamic array named “arr” in C++?
delete[] arr;
What is a dynamic array in C++?
A data structure that can change its size
Which can return the number of elements in a C++ array named “arr”?
sizeof(arr) / sizeof(arr[0])
Which header file must you include to use the std::vector class?
<vector>
</vector>