...

/

SmartPointer that Iterates through a Container

SmartPointer that Iterates through a Container

Understand the implementation of a user-defined "SmartPointer" class that iterates through a linked list container.

We'll cover the following...

Problem

Write a program that maintains a linked list using a Container class. Also, implement a SmartPointer class that lets you access Container elements using the * operator and lets you iterate through the Container using the ++ operator.

Sample run

Here’s what you should see when you run the program.

10
20
0
-40
50

Coding solution

Here is a solution to the problem above.

Press + to interact
// Smart pointer to iterate through a container
#include <iostream>
class Container
{
private :
struct node
{
int data ;
node *link ;
} *head, *current ;
int count ;
public :
Container( )
{
head = current = NULL ;
count = 0 ;
}
void add ( int n )
{
node *temp = new node ;
temp -> data = n ;
temp -> link = NULL ;
if ( head == NULL )
head = current = temp ;
else
{
node *q ;
q = head ;
while ( q -> link != NULL )
q = q -> link ;
q -> link = temp ;
}
count++ ;
}
int getcount( )
{
return count ;
}
friend class SmartPointer ;
} ;
class SmartPointer
{
private :
Container *cptr ;
public :
SmartPointer ( Container *t )
{
cptr = t ;
}
int operator *( )
{
if ( cptr->current == NULL )
return 0 ;
else
{
int i = cptr->current->data ;
return i ;
}
}
void operator ++ ( int n )
{
if ( cptr->current != NULL )
cptr->current = cptr->current->link ;
}
} ;
int main( )
{
Container c ;
c.add ( 10 ) ;
c.add ( 20 ) ;
c.add ( 0 ) ;
c.add ( -40 ) ;
c.add ( 50 ) ;
SmartPointer sptr ( &c ) ;
for ( int i = 0 ; i < c.getcount( ) ; i++ )
{
std :: cout << *sptr << std :: endl ;
sptr++ ;
}
return 0 ;
}

Explanation

A container is a way to organize data in memory. Hence stacks, linked lists, arrays are all containers. An iterator is an object that moves through a container accessing various elements of the container. We can iterate through an ordinary C++ array by using ...