Question: . Scrutinise the code shown in Figure Q 3 on page 7 . The numbers at the beginning of each line are provided for ease

. Scrutinise the code shown in Figure Q3 on page 7. The numbers at the beginning of
each line are provided for ease of reference and are not part of the program.
(a) The operators * and & have different meanings depending on whether they are
used in a declaration or an expression. Using diagrams, explain the meaning of
* used in the each of the following lines:
int* ip { new int };
*ip =1;
[2]
(b) Using English words, write out the full type of the variable vp1 which is declared
on line 22 of Figure Q3.[2]
(c) Using English words, write out the full type of the arguments of the template
function zipvectors declared on line 6.[2]
(d) Explain why the unique pointers themselves cannot be passed as arguments,
but must be passed by reference. [2]
(e) Explain what the function zipvectors does. Include the types of the arguments
and return value. Hence deduce the programs expected output. [5]
(f) the author of the function made a great effort to avoid passing vectors as
arguments. Explain why. [2]
(g) The author made no effort to avoid returning a vector from the function. Explain
why. [2]
(h) How could the type of the arguments be changed to avoid the use of pointers
but without compromise in function, safety or efficiency? [2]
When line 25 is changed to set *vp2 to {10,20} and the program is recompiled,
the following output is produced:
terminate called after throwing an instance of
'std::out_of_range'
what(): vector::_M_range_check:
__n (which is 2)>= this->size()(which is 2)
Aborted (core dumped)
(i) Why did the change result in an exception being thrown? [2]
(j) Decide on a desired behaviour when the arguments are vectors of differing length,
and write out a revised version of zipvectors incorporating the improvements
you suggested in Q3h.[4]
Page 6 of 13/OVER
1 #include
2 #include
3 #include
4
5 template
6 std::vector zipvectors(
7 std::unique_ptr> const& vptr1,
8 std::unique_ptr> const& vptr2
9)
10{
11 std::vector result;
12 result.reserve(2*vptr1->size());
13 for (int i {0} ; i < vptr1->size() ; i++){
14 result.push_back(vptr1->at(i));
15 result.push_back(vptr2->at(i));
16}
17 return result;
18}
19
20 int main()
21{
22 auto vp1{ std::make_unique>()};
23*vp1={-1,-2,-3,-4};
24 auto vp2{ std::make_unique>()};
25*vp2={2,4,6,8};
26
27 for (const int& i : zipvectors(vp1, vp2))
28 std::cout << i <<'\t';
29 std::cout << std::endl;
30
31 return 0;
32}

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Programming Questions!