Starting from:

$30

CS2134 Homework 3 Solved

Assignment 3 include a programming portion and a written portion. The programming portion must compile and consist of a single file ( hw03.cpp), and the written portion should consist of a single file (hw03written) in a .pdf format. Be sure to include your name at the beginning of each


Programming Part:

1. Write a function template called print if that:

•   takes three parameters: two iterators start, end, and a functor pred start and end have the capabilities of a forward iterator, and refer to a range

[start,end) in a container

pred is a functor that takes an element in the range [start,end) as an arguement and returns a bool

•   prints1 all items in the range [start,end) which evaluates to true

•   runs in O(n) time where n is the number of items in the range [start,end) The signature of your function template is:

template< class Itr, class UnaryPred void print_if( Itr start, Itr end, UnaryPred pred )

A small amount of extra credit will be given for figuring out how to add your own test case to the unit test for this assignment.

Written Part

1. For the vector class, and for the following code[2] snippet:

vector<int c { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 };

vector<int::iterator itr1 = c.begin()+2; vector<int::iterator itr2 = c.begin()+4; vector<int::iterator itr3 = c.begin()+8; cout << *(c.begin( ) + ( c.end( ) - c.begin( ) )/2 ) << endl;

c.erase(itr2);

cout << *itr1 << endl; cout << *itr2 << endl; cout << *itr3 << endl;

cout << *(c.begin( ) + ( c.end( ) - c.begin( ) )/2 ) << endl;

What is printed? Explain your answer.3

2.   Using big-Oh notation, give the worst case run time for the method print if, which you implemented programming problem 1.

3.   Given the following code snippet:

vector<int a {1,2,3,4, ..., n}; // vector, a, has n items vector<int::iterator itrStart; vector<int::iterator itrMid; vector<int::iterator itrEnd;

Assign values to the iterators, itrStart, itrMid, itrEnd, so that:

(a)      [itrStart, itrMid) refers to the range 1,2, 3, ..., n/2

(b)     [itrMid, itrEnd) refers to the range n/2+1,n/2+2, ..., n

4.   For each code snippet below state either why the code won’t compile/run, or state what isprinted by the code snippet.

(a)   vector<int a {1, 2, 3, 4, 5}; vector<int::iterator itra = a.begin(); cout << *(itra + 3);

(b)   list<int b {1, 2, 3, 4, 5}; list<int::iterator itrb = b.begin(); cout << *(itrb + 3);

(c)   list<int c {1, 2, 3, 4, 5}; list<int::iterator itrc = c.end(); itrc--; cout << *(itrc);

(d)   vector<int d {1, 2, 3, 4, 5}; vector<char::iterator itrd = d.begin(); cout << *(itrd + 3);


More products