CS201 – Spring 2001
Prof. Hartman
Homework #8
Due Friday, April 6th by 4:00
pm
Recommended Self-Review problems: 5.1 – 5.7
Homework to be turned in: (remember that all programs must
follow the guidelines from handout #3.)
c) After the following snippet of code what are the values of y and *y assuming that the address of x is 0x40047BC8.
int x = 25;
int *y = &x;
d) Given the snippet of code:
char *message = "Howdy!";
what is output to the screen by the following commands?
i. cout << *(message + 3) << endl;
ii. cout << message + 3 << endl;
iii. cout << (*message) + 3 << endl;
e) Given the snippet of code:
int Grog[ ] = {0, 2, 4, 6, 8};
what is output to the screen by the following commands?
i. cout << *(Grog + 3) << endl;
ii. cout << Grog + 3 << endl;
It turns out that the Standard Template Library already has a great sorting method: the sort() function. A prototype is shown below.
void sort(int *, int *, bool (* compare)(int, int))
This means that sort takes two pointers to int's and a pointer to a function. To use the sort function, you pass it a pointer to the beginning of your array as the first parameter, a pointer to the first element after your array as the second parameter (note that this second parameter is intentionally out of bounds of your array), and a pointer to a comparison function as the third parameter. The comparison function takes two int's, compares them, and returns a bool: true if the first integer is less than the second, and false otherwise. This function is located in the Standard Template Library; it is declared in the algorithm header file. This header file (like most) puts the functions in the standard namespace.
To use the function, you will need to insert the following lines of code at the beginning of your file.
#include <algorithm>
Now that you know about the STL function sort(), use it in a program that will sort an array of 100 random integers. Create your own comparison functions: one that will cause the array to be sorted in ascending order and another for descending order. Your program should sort the array twice, using the respective comparison functions, and should output the array in both ascending and descending order.