Teaching Notes: Module 08
Key Learning Objectives
Section titled “Key Learning Objectives”- STL containers (vector, list, map, stack, etc.)
- Iterators
- STL algorithms
- When to use which container
Exercise 00: easyfind
Section titled “Exercise 00: easyfind”Key Concept
Section titled “Key Concept”Generic function to find int in any container.
template <typename T>typename T::iterator easyfind(T& container, int value) { return std::find(container.begin(), container.end(), value);}Common Mistakes
Section titled “Common Mistakes”-
Not handling “not found” case
- Return iterator to end, OR throw exception
-
Forgetting typename
typename T::iterator // 'typename' required for dependent types -
Trying to use with map
- Subject says: don’t handle associative containers
- map stores pairs, not individual values
Exercise 01: Span
Section titled “Exercise 01: Span”Key Concept
Section titled “Key Concept”Store N integers, find shortest/longest span (distance).
Implementation Hints
Section titled “Implementation Hints”int Span::shortestSpan() const { if (_numbers.size() < 2) throw std::runtime_error("Not enough numbers");
std::vector<int> sorted = _numbers; std::sort(sorted.begin(), sorted.end());
int minSpan = sorted[1] - sorted[0]; for (size_t i = 2; i < sorted.size(); i++) { int span = sorted[i] - sorted[i-1]; if (span < minSpan) minSpan = span; } return minSpan;}Common Mistakes
Section titled “Common Mistakes”-
Not using STL algorithms
- Use
std::sort,std::min_element,std::max_element
- Use
-
Range addition
// Subject wants: add many numbers at oncetemplate <typename Iterator>void addNumber(Iterator begin, Iterator end); -
Testing with small data
- Subject requires testing with 10,000+ numbers
Exercise 02: MutantStack
Section titled “Exercise 02: MutantStack”Key Insight
Section titled “Key Insight”std::stack has a protected member c (the underlying container).
template <typename T>class MutantStack : public std::stack<T> {public: typedef typename std::stack<T>::container_type::iterator iterator;
iterator begin() { return this->c.begin(); } iterator end() { return this->c.end(); }};Common Mistakes
Section titled “Common Mistakes”-
Not exposing all iterator types
- iterator
- const_iterator
- reverse_iterator
-
Forgetting
this->c- Need
this->to access base class protected member
- Need
Why This Works
Section titled “Why This Works”std::stackis an adapter around a container (default:std::deque)- The container is accessible via protected member
c - We just expose its iterators
Testing
Section titled “Testing”Replace MutantStack with std::list - output should match (with appropriate method name changes).