InterviewSolution
| 1. |
Using A Smart Pointer Can We Iterate Through A Container? |
|
Answer» Answer :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. #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 ; } 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. |
|