Home C++ Introduction Decisions Loops Input/Output Functions Stack and Heap References Arrays Searching and Sorting Pointers Character and Strings Structures Classes Inheritance Exceptions Templatess Recursion STL Modern C++ Misc Books ----

Templates


Contents

Exercise

1) Fill in the TO DO parts

File:: template_ex2.cpp
#include <iostream>

using namespace std;

//TO DO
//Write a class using template that takes 2
//template parameters. The name of the class is
// TwoElementTuple . It is able to store and retrieve
// 2 items that can be of different types.
//The constructor should take 2 parameters and store them
//in the data members of the class. The data members should
//be private. There should be 2 public methods. getFirstItem and
//getSecondItem and of course the constructor should be public

//DO NOT MODIFY THE MAIN FUNCTION

int main ()
{
    TwoElementTuple< int, string> tuple1( 1, "Testing" ) ;
    cout <<  "tuple1.getFirstItem(): " <<
    tuple1.getFirstItem() << endl  ;
    cout <<  "tuple1.getSecondItem(): " <<
    tuple1.getSecondItem() << endl  ;


    return 0;
}
2) Fill in the TO DO parts

File:: template_ex3.cpp
 #include <iostream>

 using namespace std;

/*
 TO DO Convert the below code using templates
 so that it
 works with any type and not just int

*/

class MyVector
{
    public:
        int* ptr ;
        int capacity ;
        int noOfElements ;
    MyVector( int sizeP = 10 )
      {
         ptr =  new int[sizeP] ;
         capacity = sizeP ;
         noOfElements = 0 ;
      }

   void print()
      {
         for( int i1=0 ; i1 < noOfElements ; i1++ )
           {
              cout << ptr[i1] << " " ;
           }
         cout << endl ;
      }

    ~MyVector()
    {
      delete[]  ptr ;
    }
    void push_back( const int& obj1 )
    {
       if ( noOfElements < capacity )
         {
           ptr[ noOfElements ] = obj1 ;
           noOfElements++ ;
         }
      else
         {
              int* ptr1 = new int[ noOfElements*2 ]  ;
              for( int i1=0 ; i1 < noOfElements ; i1++ )
                {
                    ptr1[i1] = ptr[i1] ;
                } //
             delete[] ptr ;
             ptr = ptr1 ;

             ptr[ noOfElements ] = obj1 ;
             noOfElements++ ;
         }
    }
};



int main()
{
/*   MyVector vectorObj ;
   vectorObj.push_back( 1 ) ;
   vectorObj.push_back( 2 ) ;
   vectorObj.print() ;
*/


   MyVector<int> vectorObj ;
   vectorObj.push_back( 1 ) ;
   vectorObj.push_back( 2 ) ;
   vectorObj.print() ;

   MyVector<string> vectorObj1 ;
   vectorObj1.push_back( "one" ) ;
   vectorObj1.push_back( "two" ) ;
   vectorObj1.print() ;



}
















































Solution

1)


File:: template_ex2_s.cpp
2)


File:: template_ex2_s.cpp