CS 215 ­ Fundamentals of Programming II  Spring 2014 ­ Homework 8 20 points Out: March 24, 2014

advertisement
CS 215 ­ Fundamentals of Programming II Spring 2014 ­ Homework 8
20 points
Out: March 24, 2014
Due: March 31, 2014 (Monday)
This is a written homework assignment. Turn in a hardcopy (either handwritten or printed out).
1. (4 points) Answer the following questions concerning STL lists
(a) Declare an empty STL list variable a_list that can store integers.
(b) What is the value of a_list after the following sequence of operations:
a_list.push_back(40);
a_list.push_front(10);
a_list.push_front(15);
a_list.push_back(30);
(c) Declare an STL list variable b_list that stores 5 real numbers with initial values 1.5.
(d) What is the value of b_list after executing the following code fragment:
for (int i = 1; i <= 4; i++) {
b_list.push_front(b_list.back() + b_list.front());
b_list.pop_back();
}
2. (4 points) Answer the following questions concerning STL lists
(a) What is the value of int_list after executing the following code fragment:
list<int> int_list;
int_list.push_front(0);
list<int> iterator::iter = int_list.begin();
for (int i = 1; i <= 4; i++) {
int_list.push_front(i);
int_list.insert(iter, i);
}
(b) What is the result of the following function when called with a list containing elements: 4, ­6, 22, 7, 13, 8?
template <typename T>
void func (list <T> & a_list) {
typename list<T>::iterator iter = a_list.begin();
while (iter != a_list.end()) {
a_list.push_front (*iter);
iter = a_list.erase(iter);
}
}
03/22/2014
Page 1 of 2
D. Hwang
3. (4 points) Write a function list_split that receives a source STL list of integers and a target integer value, and passes back two STL lists of integers. The first passed back list will contain (copies of) the items from the source list that are less than the target value and the second passed back list will contain (copies of) all other items (i.e., those values greater than or equal to the target). Note that the source list is not in any particular order, and the source list must not be modified by this function.
4. (4 points) Consider a singly­linked list of Node<int> (defined in node.h from lecture) that contains integers as data items. Write a function sum_of_list that receives a pointer to the first node of a such a singly­linked list. This function returns the sum of the elements of the list.
5. (4 points) Consider a singly­linked list of Node<T> (defined in node.h from lecture). Write a template function is_ascending that receives a pointer to the first node of a singly­linked list. This function returns true if all of the elements of the list are in strictly ascending order, and false otherwise. Assume that the equality and relational operators are defined for type T.
03/22/2014
Page 2 of 2
D. Hwang
Download