You are on page 1of 3

Chapter 13.

(b) (c) (d)

6: (a) list<int> intList(arr, arr+arrSize); list<int>::iterator iter; iter = intList.begin(); // iter points at 35 // 35 // iter points at 17 // 17 // iter points at -15 // -15 (e) iter = intList.begin(); while (iter != intList.end()) { if (*iter < 0) *iter = *iter * (-1); iter++; } 14. (a) t a t a t j t j

(b) {

while (!chList.empty()) ch = chList.front(); chList.pop_front(); revList.push_front(ch);

} 16. (b) (c)

(a) template vector list begin insert template vector list begin insert switch template vector list begin switch

17. strIter = strList.begin(); while (strIter != strList.end()) { if ((*strIter).length() > 4) cout << *strIter << endl; strIter++; } 18. (b) (a) newList = + + C C + + newList = k l a w w a l k

19. 1 1 2 2 3 3 4 4 20. (a) 5 2 4 7 (b) "misp" 21. template <typename T> void rmOrderedDuplicates(list<T>& aList) { // current data value T currValue; // the two iterators we use list<T>::iterator curr, p; // start at the front of the list curr = aList.begin();

// cycle through the list while(curr != aList.end()) { // record the current list data value currValue = *curr; // set p one element to the right of curr p = curr; p++; // move forward as long as we do not encounter the end // of the list and *p equals currValue. each iteration // erases the duplicate of currValue while(p != aList.end() && *p == currValue) // erase current element and move p forward aList.erase(p++); // duplicates of currValue removed. move to the next // data value and repeat the process curr++; } } 23. (a) template <typename T> int count(const list<T>& aList, const T& item) { int numOccurrences = 0; list<T>::const_iterator iter; // scan the list using iter iter = aList.begin(); while (iter != aList.end()) { // if *iter matches item, increment numOccurrences if (*iter == item) numOccurrences++; // move iter forward iter++; } // return the number of occurrences of item return numOccurrences; } (b) template <typename T> list<T>::iterator seqSearch(list<T>::iterator first, list<T>::iterator last, const T& target) { // start at location first list<T>::iterator iter = first; // compare list elements with item until either // we arrive at last or locate item while(iter != last && !(*iter == target)) iter++; // iter either points at item or is last return iter; } template <typename T>

int count(list<T>& aList, const T& item) { int numOccurrences = 0; list<T>::iterator iter; iter = aList.begin(); while ((iter = seqSearch<T>(iter, aList.end(), item)) != aList.end()) { numOccurrences++; iter++; } // return the number of occurrences of item return numOccurrences; }

You might also like