Yes. A container is a collection of elements or objects. It helps to properly organize and store the
data. Stacks, linked lists, arrays are examples of containers. Following program shows how to iterate
through a container using a smart pointer.
Here, sp is a smart pointer. When we say *sp, the operator * ( ) function gets called. It returns the
integer being pointed to by p. When we say sp++ the operator ++ ( ) function gets called. It increments p to point to the next element in the array and then returns the address of this new location.
data. Stacks, linked lists, arrays are examples of containers. Following program shows how to iterate
through a container using a smart pointer.
#include
class smartpointer
{
private :
int *p ; // ordinary pointer
public :
smartpointer ( int n )
{
p = new int [ n ] ;
int *t = p ;
for ( int i = 0 ; i <= 9 ; i++ )
*t++ = i * i ;
}
int* operator ++ ( int )
{
return p++ ;
}
int operator * ( )
{
return *p ;
}
} ;
void main( )
{
smartpointer sp ( 10 ) ;for ( int i = 0 ; i <= 9 ; i++ )
cout << *sp++ << endl ;
}
class smartpointer
{
private :
int *p ; // ordinary pointer
public :
smartpointer ( int n )
{
p = new int [ n ] ;
int *t = p ;
for ( int i = 0 ; i <= 9 ; i++ )
*t++ = i * i ;
}
int* operator ++ ( int )
{
return p++ ;
}
int operator * ( )
{
return *p ;
}
} ;
void main( )
{
smartpointer sp ( 10 ) ;for ( int i = 0 ; i <= 9 ; i++ )
cout << *sp++ << endl ;
}
integer being pointed to by p. When we say sp++ the operator ++ ( ) function gets called. It increments p to point to the next element in the array and then returns the address of this new location.