Exercises






Exercises

Exercise 1

Suppose that you have an array of 12 int values and 2 variables of type int*:

int values[12] = { 1, 1, 2, 3, 5, 8,
  13, 21, 34, 55, 89, 144 };
const int *first, *last;

After each of the following pairs of assignments, how many elements are in the sequence pointed at by the iterator range [first, last)? Write a program to verify your conclusions.

  1. first = values; last = values + 12;

  2. first = values + 1; last = values + 2;

  3. first = values; last = values;

  4. first = values + 12; last = values + 12;

Exercise 2

Repeat the previous example, using a vector<int> instead of an array to hold the int values and using a pair of iterators of type vector<int>::const_iterator instead of pointers.

Exercise 3

Write an algorithm that takes a pair of iterators designating a writable sequence of integer values. The algorithm should double each value in the controlled sequence and store the result in place of the original value. Test the algorithm by calling it on a sequence of integer values and displaying the result.

Exercise 4

Write a class that has a function call operator that takes an argument of type int and returns a value of type int that is twice the value of its argument. Modify the algorithm you wrote for the previous exercise to take a third template argument that provides the operation to perform on each element in the sequence. Test the new algorithm and the callable type by creating an object of the callable type and passing it to the algorithm along with a pair of iterators that points to a sequence of integer values and displaying the result.

Exercise 5

Rewrite the callable type that you wrote in the previous exercise so that its constructor takes a value that it stores in the object being constructed. Instead of multiplying by 2, the function call operator should multiply its argument by that stored value. Test the new callable type by creating an object that will multiply values by 3 and passing it to the algorithm that you wrote in the previous exercise.

Exercise 6

Insert a dozen or so values of type int, in no particular order, into an object of type vector<int>, and show the contents of the controlled sequence. Insert the same series of values into an object of type set<int>, and show the contents of the controlled sequence. Insert the same series of values into an object of type unordered_set<int>, [7] and show the contents of the controlled sequence.

[7] If you haven't looked ahead, use the header <unordered_set>. The template class unordered_set is in the namespace std::tr1.



 Python   SQL   Java   php   Perl 
 game development   web development   internet   *nix   graphics   hardware 
 telecommunications   C++ 
 Flash   Active Directory   Windows