π Lecture 38 β Templates and Friends
π Overview: This lecture explores how templates interact with the friend feature in C++. It establishes four rules governing the relationship between template classes/functions and friend declarations, explaining when friendship grants access to private members across different template instantiations.
ποΈ Topics Covered
The lecture covers four rules regarding templates and friends: Rule 1 explains that ordinary functions or classes declared as friends become friends of every template instantiation. Rules 2-4 address template friends and class template friends, specifying when friendship applies to specific or all instantiations based on type parameter relationships between the granting class and the friend.
π Lecture Summary
38.1. Templates and Friends
Templates and their specializations are compatible with the friendship feature of C++. Several rules apply when dealing with templates and friend functions/classes.
38.2. Templates and Friends β Rule 1
When an ordinary function or class is declared as a friend of a class template, it becomes a friend of each instantiation of that template class. This means the ordinary friend can access private members of any instantiation of the template class.
π Definition β Rule 1: An ordinary (non-template) function or class declared as friend of a class template is a friend of every specialization of that template.
π Example (friend class): If class A is declared as friend of template<class T> class B, then A can access private data of both B<int> ib and B<char> cb.
π Example (friend function): If void doSomething(B<char>&) is declared as friend of template<class T> class B, then inside doSomething, we can access private data of both B<int> and B<char> objects.
38.3. Templates and Friends β Rule 2
Rule 2 applies when a template function or template class is made a friend of another template class. When a friend function template or friend class template is instantiated with the same type parameters as the class template granting friendship, then its instantiation for a specific type is a friend only of that class template instantiation for that particular type.
π Definition β Rule 2: Using the same type parameter T for both the class template and its template friend means friendship is restricted to matching instantiations only.
π Example: In template<class T> class B, if we declare friend void doSomething(T) and friend A<T>, then:
doSomething(5)instantiatesdoSomething<int>which can access onlyB<int>'s private data.- If inside
doSomethingwe instantiateB<int>, it's OK only whendoSomethingis instantiated forint.
π Example (error): If inside doSomething<U> we write B<int> ib, then:
doSomething( i )withint iworksdoSomething( c )withchar cgenerates error becausedoSomething<char>tries to accessB<int>but friendship was granted only when T matches
38.4. Templates and Friends β Rule 3
When a friend function/class template takes different type parameters from the class template granting friendship, then each instantiation of the friend is a friend of each instantiation of the class template granting friendship. This removes the restriction imposed by Rule 2.
π Definition β Rule 3: Using different type parameters for the class template and its template friend means every friend instantiation is a friend of every class template instantiation.
π Example: In template<class T> class B, if we declare:
template<class W> friend void doSomething(W);
template<class S> friend class A;
Then inside doSomething<U>, we can write B<int> ib even if doSomething is instantiated for char.
π Example (class): template<class T> class A can access B<char>, B<int>, or any B instantiation because friendship is universal across types.
38.5. Templates and Friends β Rule 4
Rule 4 states that when we declare a template as friend of any class, then all kinds of specializations of that template β explicit, implicit, and partial β also become friends of the class granting friendship.
π Definition β Rule 4: Declaring a template as friend grants friendship to all its specializations (implicit, explicit, partial).
π Example (functions): If template<class U> friend void doSomething(U) is declared in class B, then:
- The general template
template<class U> void doSomething(U u)can accessB<int> ib.data - Even the explicit specialization
template<> void doSomething<char>(char u)can also accessB<int> ib.data
π Example (classes): If template<class U> friend class A is declared in template<class T> class B, then:
- The general template
template<class U> class Acan accessB<int> ib.data - The partial specialization
template<class U> class A<U*>can also accessB<int> ib.data
π‘ Why this matters: Rule 2 is the most complex and requires careful attention. Rules 1, 3, and 4 are simpler β Rule 1 for ordinary friends, Rule 3 for template friends with different type parameters, and Rule 4 extending friendship to all specializations.
β Key Takeaways
Rule 1 establishes that ordinary (non-template) friends of a class template gain access to all its instantiations. Rule 2 restricts friendship to matching type instantiations when the same type parameter is used for both the class template and its template friend. Rule 3 provides universal friendship when different type parameters are used β each friend instantiation can access any class template instantiation. Rule 4 extends friendship to all specializations (explicit, implicit, partial) of a template declared as friend. The most challenging for students is Rule 2, where mismatched instantiations cause compilation errors if a friend template tries to access a class template instantiation of a different type.
π§ Quick Revision Questions
- Under Rule 1, if
class Ais declared as friend oftemplate<class T> class B, which instantiations of B can class A access? - In Rule 2, what happens if inside
doSomething<U>we instantiateB<int>but calldoSomething('c')from main? - How does Rule 3 differ from Rule 2 regarding the type parameters used in friend declarations?
- According to Rule 4, if we declare
template<class U> friend class Ain a class template, does the partial specializationA<U*>have friend access? - What is the key difference in behavior between Rule 1 (ordinary friend) and Rule 2 (template friend with same type parameter)?
π Lecture 39 β Templates & Static Members
π Overview: This lecture explores the behavior of static members within template classes, demonstrating how each instantiation of a template class has its own copy of static data members. It concludes the topic of templates with advantages and disadvantages, then revisits generic algorithms by applying them to a custom Vector container class.
ποΈ Topics Covered
The lecture covers static members in template classes with examples showing separate copies for different data types and shared copies for same type objects. It concludes the templates topic with advantages and disadvantages, then revisits generic algorithms by applying the find algorithm to a custom Vector container class, discussing implementation details and problems with the current approach.
π Lecture Summary
39.1. Templates & Static Members
In template classes, static members behave similarly to general classes, but with a crucial difference: each instantiation of a template class for a different data type gets its own copy of static data members. When the compiler creates template class implementations for different data types as required, each implementation has its own copy of static members.
π Definition β Static Members in Template Classes: Static members in template classes are created when the template class is instantiated for each data type, and each instantiation has its own separate copy of static data members.
π Formula: template<class T> int A<T>::data = 0; β This initializes the static member data to 0 for each instantiation of template class A.
π Example 1 β Separate copies for different types:
template< class T > class A {
public:
static int data;
};
template<class T> int A<T>::data = 0;
int main() {
A< int > ia; // gets its own data
A< char > ca; // gets separate data
ia.data = 5;
ca.data = 7;
// Output: ia.data = 5, ca.data = 7
}
This demonstrates that A<int> and A<char> have independent static data members.
π Example 2 β Same type objects share static members:
A< int > ia, ib, ic; // all share same static data
ia.data = 5;
ib.data = 7;
ic.data = 9;
// Output: ia.data = 9, ib.data = 9, ic.data = 9
All objects of the same type (A<int>) share a single copy of the static member.
π‘ Why this matters: Understanding that each template instantiation gets its own static members is crucial for correctly managing shared state in generic programming, especially when using static counters or shared resources.
39.2. Templates β Conclusion
Advantages of Templates:
- Reusability: Write code once for all data types
- Writability: Less code to write and maintain
Disadvantages of Templates:
- Can consume memory if used without care
- Reliability issues: Templates give the same implementation for all data types, which may not be correct for a particular data type
π Example of reliability problem:
template< typename T >
bool isEqual( T x, T y ) {
return ( x == y );
}
This function produces incorrect results for char* because it compares memory addresses (first character only) instead of string contents:
char* str1 = "Hello";
char* str2 = "World!";
isEqual( str1, str2 ); // Compiles but gives wrong result
39.3. Generic Algorithms Revisited
A generic algorithm is type-independent and independent of the underlying data structure. The find algorithm developed earlier is an example:
template< typename P, typename T >
P find( P start, P beyond, const T& x ) {
while ( start != beyond && *start != x )
++start;
return start;
}
π Definition β Generic Algorithm: An algorithm that works for any aggregate object (container) that defines three operations: increment operator (++), dereferencing operator (*), and inequality operator (!=).
39.4. Generic Algorithms Revisited (continued)
To apply the generic find algorithm to a custom Vector template class, the Vector must support three operations:
- Increment operator (
++) - Dereferencing operator (
*) - Inequality operator (
!=)
The modified Vector class adds an integer data member index to track traversal position, with getter (getIndex()) and setter (setIndex()) methods.
Key Vector operators implementation:
operator++(): Increments index if less than sizeoperator*(): Returnsptr[index]operator!=(): Compares size and index, then element-by-element comparison
π Example β Applying find to Vector:
int main() {
Vector<int> iv(3); // First Vector: stores data
iv[0] = 10; iv[1] = 20; iv[2] = 30;
Vector<int> beyond(iv); // Second Vector: marks end
beyond.setIndex(3); // Points beyond last element
Vector<int> found(3); // Third Vector: stores result
found = find(iv, beyond, 20);
cout<<"Index: "<<found.getIndex(); // Output: Index: 1
}
39.5. Generic Algorithm (execution)
The find algorithm iterates through Vector elements:
| Iteration | iv size | beyond size | iv index | beyond index | start != beyond | *start != x |
|---|---|---|---|---|---|---|
| 1 | 3 | 3 | 0 | 3 | true | true |
| 2 | 3 | 3 | 1 | 3 | true | true (found 20 at index 1, loop exits) |
| 3 | 3 | 3 | 2 | 3 | true | undefined (not reached) |
| 4 | 3 | 3 | 3 | 3 | false | undefined |
The algorithm stops at iteration 2 when element 20 is found, returning Vector with index = 1.
39.6. Problems
Three major problems exist with this generic algorithm implementation:
a. No support for multiple traversals: Can only move forward in single steps, which is inefficient for large Vector objects. No facility for simultaneous forward and reverse traversal.
b. Inconsistent behavior: Uses whole container objects as markers instead of simple pointers. The found object is returned when a simple pointer would suffice.
c. Single traversal strategy only: No way to change traversal strategy (e.g., moving beyond more than one value in a single step).
β Key Takeaways
This lecture demonstrates that template classes create separate static members for each data type instantiation, a critical distinction from general classes. The find algorithm showcases generic programming's power but reveals limitations when applied to custom containers like Vector, which requires proper operator overloading for ++, *, and !=. The three main problems with the current approachβlack of multiple traversals, inconsistent use of containers as markers, and single traversal strategyβhighlight the need for a more robust abstraction like iterators. Students must understand that while templates offer reusability, they can lead to reliability issues when the same implementation is inappropriate for certain data types (e.g., char* comparison).
π§ Quick Revision Questions
- What happens to static data members when a template class is instantiated for two different data types (e.g.,
A<int>andA<char>)? - Why does the
isEqualfunction template produce incorrect results forchar*pointers? - What three operations must a container support for the generic
findalgorithm to work? - In the Vector example, why must three separate Vector instances be created to use the
findalgorithm? - What are the three main problems identified with the current generic algorithm implementation?
π Lecture 40 β Iterators
π Overview: This lecture addresses the limitations of using external pointers (cursors) for container traversal, particularly the violation of data hiding and issues with non-contiguous containers. It introduces Iterators as a superior solution that allows multiple traversals on a single container without exposing its internal representation, while maintaining data abstraction and encapsulation principles.
ποΈ Topics Covered
The lecture first reviews the drawbacks of the previous approach using external pointers for container traversal, including no support for multiple traversals and inconsistent behavior. It then introduces cursors (external pointers) as an improvement, demonstrating their implementation in a Vector class with first(), beyond(), and next() methods. The lecture examines how cursors work well for contiguous containers like arrays but fail with non-contiguous containers like Sets. Finally, it presents Iterators as the complete solution β internal objects that traverse containers while hiding internal representation, implemented as a generic template class with operator overloading.
π Lecture Summary
Recap β Limitations of External Pointers
Previously, the generic find algorithm was applied to custom containers by supporting three operations: * (dereference), ++ (increment), and != (inequality comparison). However, this approach required creating three distinct Vector objects for a single find operation, which is inefficient for large containers. The major drawbacks included no support for multiple simultaneous traversals, support for only a single traversal strategy, and inconsistent behavior.
40.1. Cursors
Cursors are external pointers declared outside the container/aggregate object that traverse its elements. The aggregate object provides three helper methods to support cursor traversal:
T* first()β returns pointer to first elementT* beyond()β returns pointer to one position past the last elementT* next(T*)β returns pointer to the next element
π Example β Vector Class Implementation:
template<class T>
T* Vector<T>::first() {
return ptr;
}
template<class T>
T* Vector<T>::beyond() {
return (ptr + size);
}
template<class T>
T* Vector<T>::next(T* current) {
if (current < (ptr + size))
return (current + 1);
return current;
}
π‘ Why this matters: Using cursors eliminates the need to create multiple Vector objects for traversal. Instead, we create multiple pointers (cursors) pointing into the same Vector object, which is far more memory-efficient.
π Example β Using Cursors:
int main() {
Vector<int> iv(3);
iv[0] = 10; iv[1] = 20; iv[2] = 30;
int* first = iv.first();
int* beyond = iv.beyond();
int* found = find(first, beyond, 20);
return 0;
}
The generic find method remains unchanged:
template<typename P, typename T>
P find(P start, P beyond, const T& x) {
while (start != beyond && *start != x)
++start;
return start;
}
Limitation β Non-contiguous containers: Cursors work fine for contiguous sequences like C++ arrays or Vector (implemented with arrays) where elements are at consecutive memory locations. However, cursors fail with non-contiguous containers (like Set, which will be studied later). The ++ operation on a simple pointer doesn't work because elements are not placed at consecutive memory addresses.
π Example β Problem with Set:
int main() {
Set<int> is(3);
is.add(10); is.add(20); is.add(30);
ET* first = iv.first(); // Error β incompatible types
ET* beyond = iv.beyond(); // Error
ET* found = find(first, beyond, 20); // Error β ++start fails
}
Solution for non-contiguous containers: Use the container's own traversal operations:
template<typename CT, typename ET>
P find(CT& cont, const ET& x) {
ET* start = cont.first();
ET* beyond = cont.beyond();
while (start != beyond && *start != x)
start = cont.next(start);
return start;
}
Cursors β Conclusion: The main benefit is using external pointers, allowing any number of simultaneous traversals β one pointer for each traversal. However, cursors cannot replace pointers for all containers.
40.2. Iterators
Iterators are internal data members of a container that traverse it without exposing its internal representation. They are for containers exactly like pointers are for ordinary data structures. Unlike cursors, iterators do not violate data hiding principles.
π Definition β Iterator: An object that allows traversing a container's elements while maintaining data abstraction by emulating pointer behavior through operator overloading.
Generic Iterators: A general Iterator class can point to any container because it is implemented using templates. The container must still provide three methods: first(), beyond(), and next().
π Example β Generic Iterator Class:
template<class CT, class ET>
class Iterator {
CT* container;
ET* index;
public:
Iterator(CT* c, bool pointAtFirst = true);
Iterator(Iterator<CT, ET>& it);
Iterator& operator ++();
ET& operator *();
bool operator !=(Iterator<CT, ET>& it);
};
Constructor: Takes a pointer to a container and a boolean flag. If pointAtFirst is true, index points to the first element; otherwise, it points to beyond the last element.
template<class CT, class ET>
Iterator<CT,ET>::Iterator(CT* c, bool pointAtFirst) {
container = c;
if (pointAtFirst)
index = container->first();
else
index = container->beyond();
}
π Example β Complete Iterator Usage:
int main() {
Vector<int> iv(2);
iv[0] = 10; iv[1] = 20;
// Create two Iterator objects for the SAME Vector object
Iterator<Vector<int>, int> it(&iv); // points to first element
Iterator<Vector<int>, int> beyond(&iv, false); // points beyond last
Iterator<Vector<int>, int> found = find(it, beyond, 20);
return 0;
}
π‘ Why this matters: We are NOT creating multiple Vector objects! We create multiple Iterator objects against one Vector object, which is efficient and respects data hiding.
Iterators β Advantages
- Multiple traversals: More than one traversal can be pending on a single container simultaneously
- Flexible strategy: Iterators allow changing the traversal strategy without changing the aggregate object
- Data abstraction: They contribute towards data abstraction by emulating pointers without exposing internal details
β Key Takeaways
Cursors provide external pointers for container traversal but violate data hiding and fail with non-contiguous containers. Iterators solve both problems by being internal objects that traverse containers while hiding their internal representation. The Iterator class is implemented as a generic template requiring two type parameters (container type and element type) and overloads three operators: *, ++, and !=. The container must still provide first(), beyond(), and next() methods, but these are accessed through the Iterator, not directly by client code. The key advantage is that multiple Iterator objects can traverse the same container object without creating duplicate containers.
π§ Quick Revision Questions
- What are the three main drawbacks of using external pointers for container traversal?
- Explain why cursors work for Vector but fail for Set containers.
- What is the fundamental difference between cursors and iterators regarding data hiding?
- Why does the Iterator class require two template parameters (CT and ET)?
- How does the Iterator constructor distinguish between pointing to the first element versus beyond the last element?
π Lecture 41 β Standard Template Library
π Overview: This lecture introduces the Standard Template Library (STL), a collection of standardized, reusable C++ template solutions for common programming problems. It covers the three core components of STLβcontainers, iterators, and algorithmsβand provides a detailed examination of various container types, including sequence containers, associative containers, and container adapters, along with their common functions.
ποΈ Topics Covered
The lecture begins with an introduction to the STL and its three key components: containers, iterators, and algorithms. It then delves into STL containers, categorizing them into sequence containers (vector, deque, list), associative containers (set, multiset, map, multimap), and container adapters (stack, queue, priority_queue). The discussion includes examples for each container type, followed by an overview of common functions applicable to all containers and those specific to first-class containers. Finally, it covers container requirements, emphasizing the need for copy, assignment, and comparison operators in element classes.
π Lecture Summary
41.1. Standard Template Library:
The Standard Template Library (STL) is a collection of standardized, reusable C++ template solutions for common programming problems like searching and comparison. These solutions were developed and approved by the C++ standardization committee to operate efficiently across many different applications. STL consists of three key components: Containers, Iterators, and Algorithms. STL promotes reuse by eliminating the need to rewrite standard code, saving development time and cost. These solutions are thoroughly tested, reducing the chance of errors.
41.2. STL Containers
A Container is an object that holds a collection of data elements. STL provides three kinds of containers: Sequence Containers, Associative Containers, and Container Adapters.
Sequence Containers: A sequence organizes a finite set of objects, all of the same type, into a strictly linear arrangement. These include:
- vector: Supports rapid insertions and deletions at the back end and random access to elements.
- deque: Behave like a queue, supporting rapid insertions and deletions at the front or back, and random access to elements.
- list: A doubly linked list that allows rapid insertions and deletions anywhere. A list is a linear data structure, but access to elements requires sequential movement from the start.
π‘ Why this matters: Sequence containers maintain elements in a linear order, but each type offers different performance trade-offs for insertion, deletion, and access operations, making it crucial to choose the right container for a given task.
Example β STL Vector: This code snippet demonstrates the use of a std::vector<int>. The user enters two integers, which are added to the vector using push_back(). The program outputs the current capacity and size of the vector.
#include <vector>
int main() {
std::vector<int> iv;
int x, y;
char ch;
do {
cout<<"Enter the first integer:";
cin >> x;
cout<<"Enter the second integer:";
cin >> y;
iv.push_back( x );
iv.push_back( y );
cout << βCurrent capacity of iv = β << iv.capacity() << endl;
cout << βCurrent size of iv =β<< iv.size() << endl;
cout<<"Do you want to continue?";
cin >> ch;
} while ( ch == 'y' );
return 0;
}
Sample Output:
Enter the first integer: 1
Enter the second integer: 2
Current capacity of iv = 2
Current size of iv = 2
Do you want to continue? y
Enter the first integer: 3
Enter the second integer: 4
Current capacity of iv = 4
Current size of iv = 4
Do you want to continue? y
Enter the first integer: 5
Enter the second integer: 6
Current capacity of iv = 8
Current size of iv = 6
Do you want to continue? n
π Formula: capacity() returns the currently allocated storage space for the vector (which can grow automatically), while size() returns the number of elements currently stored. The capacity grows dynamically as needed (e.g., from 4 to 8 in the output) to accommodate more elements.
Example β STL Deque: This code snippet demonstrates the use of a std::deque<int>, adding elements at the front and back, and removing them from the front and back.
#include <deque>
int main() {
std::deque<int> dq;
dq.push_front( 3 );
dq.push_back( 5 );
dq.pop_front();
dq.pop_back();
return 0;
}
Example β STL List: This code snippet demonstrates the use of a std::list<float> and an iterator. It adds elements to the list and inserts a new element at a specific position using an iterator.
#include <list>
int main() {
std::list<float> _list;
_list.push_back( 7.8 );
_list.push_back( 8.9 );
std::list<float>::iterator it = _list.begin();
_list.insert( ++it, 5.3 );
return 0;
}
Associative Containers: An associative container provides fast retrieval of data based on keys. Elements are added using a key-based formula (e.g., value % 10) and retrieved using the same formula, allowing direct access without sequential traversal.
π Definition β Associative Container: A container that provides fast retrieval of data based on keys, eliminating the need for linear search.
Associative containers include:
- set: No duplicates allowed.
- multiset: Duplicates allowed.
- map: No duplicate keys allowed.
- multimap: Duplicate keys allowed.
Example β STL Set: This code snippet demonstrates a std::set<char>. It inserts characters 'a', 'b', and 'b' again, and the output shows a size of 2 because sets do not allow duplicates.
#include <set>
int main() {
std::set<char> cs;
cout << βSize before insertions: β << cs.size() << endl;
cs.insert( βaβ );
cs.insert( βb' );
cs.insert( βb' );
cout << βSize after insertions: β << cs.size();
return 0;
}
Output:
Size before insertions: 0
Size after insertions: 2
Example β STL Multi-Set: This code snippet demonstrates a std::multiset<char>, which allows duplicates. The output shows a size of 3 after inserting 'a', 'b', and 'b'.
#include <set>
int main() {
std::multiset<char> cms;
cout << "Size before insertions: " << cms.size() << endl;
cms.insert( 'a' );
cms.insert( 'b' );
cms.insert( 'b' );
cout << "Size after insertions: " << cms.size();
return 0;
}
Output:
Size before insertions: 0
Size after insertions: 3
Example β STL Map: This code snippet demonstrates a std::map<int, char>. It inserts key-value pairs (1,'a'), (2,'b'), (3,'c') and uses find(2) to retrieve the iterator and print the value at key 2.
#include <map>
int main() {
typedef std::map<int, char> MyMap;
MyMap m;
m.insert(MyMap::value_type(1, 'a'));
m.insert(MyMap::value_type(2, 'b'));
m.insert(MyMap::value_type(3, 'c'));
MyMap::iterator it = m.find( 2 );
cout << "Value @ key " << it->first << " is " << it->second;
return 0;
}
Output:
Value @ key 2 is b
Example β STL Multi-Map: This code snippet demonstrates a std::multimap<int, char>, which allows duplicate keys. It inserts (1,'a'), (2,'b'), (3,'b') and retrieves values at keys 2 and 3.
#include <map>
int main() {
typedef std::multimap<int, char> MyMap;
MyMap m;
m.insert(MyMap::value_type(1, 'a'));
m.insert(MyMap::value_type(2, 'b'));
m.insert(MyMap::value_type(3, 'b'));
MyMap::iterator it1 = m.find( 2 );
MyMap::iterator it2 = m.find( 3 );
cout << "Value @ key " << it1->first << " is " << it1->second << endl;
cout << "Value @ key " << it2->first << " is " << it2->second << endl;
return 0;
}
Output:
Value @ key 2 is b
Value @ key 3 is b
First-class Containers: Sequence and associative containers are collectively referred to as the first-class containers.
Container Adapters: A container adapter is a constrained version of a first-class container. These include:
- stack: Follows Last In First Out (LIFO) principle. It can adapt a vector, deque, or list.
- queue: Follows First In First Out (FIFO) principle. It can adapt a deque or list.
- priority_queue: Also follows FIFO, but elements are added according to a priority (e.g., a printer queue with priority options). It can adapt a vector or deque.
41.3. Common Functions for All Containers
These are general functions that can be used with any container class:
- Default constructor
- Copy Constructor
- Destructor
- empty(): Returns true if the container contains no elements.
- max_size(): Returns the maximum number of elements the container can hold.
- size(): Returns the current number of elements.
operator = (): Assigns one container instance to another.operator < (): Returns true if the first container is less than the second.operator <= (): Returns true if the first container is less than or equal to the second.operator > (): Returns true if the first container is greater than the second.operator >= (): Returns true if the first container is greater than or equal to the second.operator == (): Returns true if the first container is equal to the second.operator != (): Returns true if the first container is not equal to the second.- swap(): Swaps the elements of two containers.
41.4. Functions for First-class Containers
First-class containers (sequence and associative) have the following additional functions:
- begin(): Returns an iterator object referring to the first element of the container.
- end(): Returns an iterator object referring to the position just beyond the last element.
- rbegin(): Returns an iterator object referring to the last element of the container (reverse begin).
- rend(): Returns an iterator object referring to the position before the first element (reverse end).
- erase(iterator): Removes an element pointed to by the iterator.
- erase(iterator, iterator): Removes a range of elements specified by two iterators.
- clear(): Erases all elements from the container.
41.5. Container Requirements
Elements added to containers must provide basic functionality because containers perform operations like copying and comparison on them.
-
When an element is inserted, a copy of that element is made using the Copy Constructor and Assignment Operator. Therefore, elements must support copying and assignment. Built-in C++ data types already provide this, and the compiler generates a default copy constructor and assignment operator for user-defined types (classes/structures) if not explicitly defined.
-
Associative containers and many algorithms compare elements. Therefore, elements must support the
operator ==andoperator <for comparison. C++ does not provide comparison operators by default for user-defined types, so developers must define them in the element class to use it in associative containers.
β Key Takeaways
- The STL has three core components: containers (which hold data), iterators (which navigate through data), and algorithms (which process data).
- Sequence containers (vector, deque, list) maintain a linear arrangement with different performance characteristics; associative containers (set, map, etc.) use keys for fast retrieval and do not allow or allow duplicates based on the type; container adapters (stack, queue, priority_queue) provide constrained interfaces.
- Common functions like
size(),empty(),begin(),end(), anderase()are available across all containers, with first-class containers having additional functions likerbegin(),rend(), andclear(). - For elements to be used in STL containers, they must support copy construction and assignment. For use in associative containers and algorithms, they must also support
operator ==andoperator <. - The STL promotes code reuse and reliability by providing thoroughly tested, standard solutions that save development time and reduce errors.
π§ Quick Revision Questions
- What are the three key components of the Standard Template Library (STL)?
- Name two sequence containers and two associative containers. What is the main difference in how they organize data?
- In the STL
vectorexample, why did the capacity change from 4 to 8 after adding elements in the third iteration? - What is a container adapter? Give one example and explain the principle it follows (e.g., FIFO or LIFO).
- Why must a user-defined class provide its own
operator ==andoperator <if its objects are to be used in an STL associative container likestd::set?
π Lecture 42 β Iterators
π Overview: This lecture provides a comprehensive overview of STL Iterators in C++, covering the different categories of iterators, their capabilities, and which container types support them. Understanding iterators is essential for efficiently traversing and manipulating STL containers without accessing their internal details.
ποΈ Topics Covered
The lecture covers STL iterators and their categories including input, output, forward, bidirectional, and random-access iterators. It explains which iterator types are compatible with different container categories (sequence containers, associative containers, and container adapters), details the operations supported by each iterator category, and provides multiple code examples demonstrating iterator usage. The lecture concludes with an introduction to STL algorithms that work with iterators.
π Lecture Summary
42.1. Iterators
We have studied about Iterators before; they are used to traverse Containers efficiently without accessing internal details. Now we see Iterators provided to us in standard template library. STL Iterators provide pointer operations such as * and ++, and they work for containers like pointers work for ordinary data structures.
π‘ Why this matters: Iterators provide a uniform interface for accessing elements in different container types, allowing algorithms to work with any container without knowing its internal structure.
42.2. Iterator Categories
We can divide Iterators given to us in STL in the following categories:
a. Input Iterators b. Output Iterators c. Forward Iterators d. Bidirectional Iterators e. Random-access Iterators
Input Iterators Using input iterators we can read an element, and we can only move in forward direction one element at a time. These can be used in implementing those algorithms that can be solved in one pass (moving container once in single direction from start to end like the find algorithm we studied in last lecture).
Output Iterators Using output iterators we can read an element, and we can only move in forward direction one element at a time. These can be used in implementing those algorithms that can be solved in one pass (moving container once in single direction from start to end like the find algorithm we studied in last lecture).
Forward Iterators Forward iterators have the capabilities of both input and output Iterators. In addition, they can bookmark a position in the container (we can set one position as a bookmark while traversing the container, which will be more understandable when we see the example below).
Bidirectional Iterators They have all the capabilities of forward Iterators plus they can be moved in backward direction. As a result, they support multi-pass algorithms (algorithms that need to traverse the container more than once).
Random Access Iterators They have all the capabilities of bidirectional Iterators plus they can directly access any element of a container.
42.3. Iterator Summary
The following diagram shows the capabilities and scope of different iterators. You can see that Random access iterators have all the capabilities and input and output iterators have the least capabilities.
Forward
Input
Output
Random Access
Bidirectional
Forward
Input Output
42.4. Container and Iterator Types
We can use different types of iterators with different types of containers (according to the nature of the container).
42.5. Sequence Containers
| Container Type | Iterator Type | Reason |
|---|---|---|
| vector | random access | (as we can access any element of vector using its index, so we can use random access iterator) |
| deque | random access | (in deque we can add elements only in front and back, however we can access any element of deque using its index, so we can use random access Iterator) |
| list | bidirectional | (in list we can move in both directions in sequence, however cannot access an element at specific index randomly, so we can use bidirectional iterator with list) |
42.6. Associative Containers
In associative containers we save values based on keys, and we cannot access elements randomly based on indexes as elements are not stored at contiguous memory locations. However, we can traverse them in both directions, so we can use bidirectional iterators with them.
| Container Type | Iterator Type |
|---|---|
| set | bidirectional |
| multiset | bidirectional |
| map | bidirectional |
| multimap | bidirectional |
42.7. Container Adapters
Container adapters are made with special restrictions. The most important restriction is that they don't allow free traversal of their elements, so we CANNOT use iterators with them.
| Container Type | Iterator Type |
|---|---|
| stack | (none) |
| queue | (none) |
| priority_queue | (none) |
42.8. Iterator Operations
Iterators support the following operations:
All Iterators support:
p1 = p2β Assignment (two Iterators)p1 == p2β Equality operatorp1 != p2β Inequality operatorp->β Member access operator
Input Iterators support:
++pβ Pre-increment an iteratorp++β Post-increment an Iterator*pβ Dereference operator used as rvalue (right value, meaning they can be used on right side of expression) for reading only, not for assigning value as lvalue (left value, assignment only taken place when we are allowed to use them as left value)
Output Iterators support:
*pβ Dereference operator (here we can use it for assigning new value as lvalue because the iterator is an output iterator that can be used to set any value)p1 = p2β Assignment
Forward Iterators: As Forward Iterators have combined properties of both input and output iterators, they support operations of both input and output Iterators.
Bidirectional Iterators: As bidirectional iterators can move in backward direction also, they support decrementing operations (moving pointer one element back):
--pβ Pre-decrement operatorp--β Post-decrement operator
Random-access Iterators: Besides the operations of bidirectional Iterators, they also support:
Access Operator:
p + iβ Result is an iterator pointing at p + ip β iβ Result is an iterator pointing at p β ip += iβ Increment iterator p by i positionsp β= iβ Decrement iterator p by i positionsp[ i ]β Returns a reference of element at p + ip1 < p2β Returns true if p1 is before p2 in the containerp1 <= p2β Returns true if p1 is before p2 in the container or p1 is equal to p2p1 > p2β Returns true if p1 is after p2 in the containerp1 >= p2β Returns true if p1 is after p2 in the container or p1 is equal to p2
Example β Random Access Iterator
typedef std::vector< int > IntVector;
int main() {
const int SIZE = 3;
int iArray[ SIZE ] = { 1, 2, 3 };
IntVector iv(iArray, iArray + SIZE);
IntVector::iterator it = iv.begin();
cout << "Vector contents: ";
for ( int i = 0; i < SIZE; ++i )
cout << it[i] << ", ";
return 0;
}
Sample Output: Vector contents: 1, 2, 3,
Example β Bidirectional Iterator (using index operator β ERROR)
typedef std::set< int > IntSet;
int main() {
const int SIZE = 3;
int iArray[ SIZE ] = { 1, 2, 3 };
IntSet is( iArray, iArray + SIZE );
IntSet::iterator it = is.begin();
cout << "Set contents: ";
for (int i = 0; i < SIZE; ++i)
cout << it[i] << ", "; // Error β cannot use [] with bidirectional iterator
return 0;
}
Example β Bidirectional Iterator (using increment operator β CORRECT)
typedef std::set< int > IntSet;
int main() {
const int SIZE = 3;
int iArray[ SIZE ] = { 1, 2, 3 };
IntSet is( iArray, iArray + SIZE );
IntSet::iterator it = is.begin();
cout << "Set contents: ";
for ( int i = 0; i < SIZE; ++i )
cout << *it++ << ", "; // OK
return 0;
}
Sample Output: Set contents: 1, 2, 3,
Example β Bidirectional Iterator (traversing backward)
typedef std::set< int > IntSet;
int main() {
const int SIZE = 3;
int iArray[ SIZE ] = { 1, 2, 3 };
IntSet is( iArray, iArray + SIZE );
IntSet::iterator it = is.end();
cout << "Set contents: ";
for (int i = 0; i < SIZE; ++i)
cout << *--it << ", ";
return 0;
}
Sample Output: Set contents: 3, 2, 1,
Example β Input Iterator
#include <iostream>
using std::cin;
using std::cout;
using std::endl;
#include <iterator>
int main() {
int x, y, z;
cout << "Enter three integers:\n";
std::istream_iterator< int > inputIt( cin );
x = *inputIt++;
y = *inputIt++;
z = *inputIt;
cout << "x = " << x << endl;
cout << "y = " << y << endl;
cout << "z = " << z << endl;
return 0;
}
Example β Output Iterator (trying to write to input iterator β ERROR)
int main() {
int x = 5;
std::istream_iterator< int > inputIt( cin );
*inputIt = x; // Error β cannot assign to input iterator
return 0;
}
Example β Output Iterator
int main() {
int x = 1, y = 2, z = 3;
std::ostream_iterator< int > outputIt( cout, ", " );
*outputIt++ = x;
*outputIt++ = y;
*outputIt++ = z;
return 0;
}
Example β Output Iterator (trying to read from output iterator β ERROR)
int main() {
int x = 1, y = 2, z = 3;
std::ostream_iterator< int > outputIt( cout, ", " );
x = *outputIt++; // Error β cannot read from output iterator
return 0;
}
42.9. Algorithms
STL includes 70 standard algorithms.
These algorithms may use Iterators to manipulate containers.
STL algorithms also work for ordinary pointers and data structures.
An algorithm works with a particular container only if that container supports a particular Iterator category.
A multi-pass algorithm, for example, requires bidirectional Iterator(s) at least.
Algorithm Examples:
Mutating-Sequence Algorithms (that require changing of elements position):
copycopy_backwardfillfill_ngenerategenerate_niter_swappartition- ...others...
Non-Mutating-Sequence Algorithms (that don't require changing of element position):
adjacent_findcountcount_ifequalfindfind_eachfind_endfind_first_of- ...others...
Numeric Algorithms (involves mathematical calculation):
accumulateinner_productpartial_sumadjacent_difference
Example β copy Algorithm
#include <iostream>
using std::cout;
#include <vector>
#include <algorithm>
typedef std::vector< int > IntVector;
int main() {
int iArray[] = {1, 2, 3, 4, 5, 6};
IntVector iv( iArray, iArray + 6 );
std::ostream_iterator< int > output( cout, ", " );
std::copy( iv.begin(), iv.end(), output );
return 0;
}
Output: 1, 2, 3, 4, 5, 6,
Example β fill Algorithm
#include <iostream>
using std::cout;
using std::endl;
#include <vector>
#include <algorithm>
typedef std::vector< int > IntVector;
int main() {
int iArray[] = { 1, 2, 3, 4, 5 };
IntVector iv( iArray, iArray + 5 );
std::ostream_iterator< int > output( cout, ", " );
std::copy( iv.begin(), iv.end(), output );
std::fill(iv.begin(), iv.end(), 0);
cout << endl;
std::copy( iv.begin(), iv.end(), output );
return 0;
}
β Key Takeaways
The five categories of STL iterators form a hierarchy where each adds capabilities: input iterators (read-only forward), output iterators (write-only forward), forward iterators (read/write with bookmarking), bidirectional iterators (forward/backward traversal for multi-pass algorithms), and random-access iterators (direct element access with arithmetic operations). Container-iterator compatibility is determined by container structure: vector and deque support random-access iterators, list and all associative containers (set, multiset, map, multimap) support bidirectional iterators, while container adapters (stack, queue, priority_queue) do not support iterators at all. STL algorithms like copy and fill work with iterators to manipulate containers, and an algorithm's required iterator category determines which containers it can operate on.
π§ Quick Revision Questions
- What is the key difference between a forward iterator and a bidirectional iterator?
- Why can't you use a random-access iterator with a
listcontainer? - What operations does an input iterator support that an output iterator does not, and vice versa?
- Which iterator category is required for multi-pass algorithms, and why?
- What happens when you try to use the
[]operator (indexing) with aset::iterator?