13. Vectors¶
Q) Adding to a Vector¶
Consider the following function which is trying to create a vector of 100 odd numbers
vector<int> find100Odd()
{
vector<int> odds;
int i = 0;
while (odds.size() < 100) {
if (i % 2 == 1) {
// STATEMENT HERE
}
i++;
}
return odds;
}
Which of the following lines completes the above program?
a. odds.at(data.size()) = i;
b. odds.push_back(i);
c. odds.at(0) = i;
d. return odds.at(0) = i;
Q) foo() Vector Function¶
What does the following code do (assume data is not empty)?
void foo(vector<int> data)
{
int found = data.at(0);
for (unsigned int i = 0; i < data.size(); i++) {
if (data.at(i) < found) {
found = data.at(i);
}
}
cout << found << endl;
}
a. Function prints if it is able to find a specific value in its vector parameter.
b. Function prints the first element of its vector parameter.
c. Function prints the minimum value in its vector parameter.
d. Function prints the last element of its vector parameter.
Q) Guess bar()
output¶
What is the output of the following code, and why?
void bar(vector<int> data)
{
for (unsigned int i = 0; i < data.size(); i++) {
data.at(i) = data.at(i) / 2;
}
}
int main_x()
{
vector<int> ages {15};
bar(ages);
cout << ages.at(0) << endl;
return 0;
}
a. 15 because of pass-by-value.
b. 15 because of pass-by-reference.
c. 7 because of pass-by-value.
d. 7 because of pass-by-reference.
Q) Reorder the Vector Statements¶
The options below are lines of C++ code that can be used to construct a function. This function should make the first two elements of its vector parameter trade places.
For example, when called with:
vector<double> data {10.0, 20.5, 30.9};
tradePlaces(data);
then data should end up being {20.5, 10.0, 30.9}
.
The lines of code are in the correct order, but you must choose which of them must be used (select them), and which must be ignored (don't select them).
1. void tradePlaces(vector<double> data) {
2. void tradePlaces(vector<double> &data) {
3. double temp = data.at(0);
4. double temp = data.at(1);
5. data.at(1) = data.at(0);
6. data.at(1) == data.at(0);
7. data.at(0) = temp;
8. return data;
9.}
Answers¶
b. odds.push_back(i);
c. Function prints the minimum value in its vector parameter.
d. 7 because of pass-by-reference.
Keep the following:
2. void tradePlaces(vector