Solved

Arrays/Templates Help

Posted on 2004-09-22
11
287 Views
Last Modified: 2010-05-18
Hi,

I am taking a class, which is basically a introduction to C++.  Here is one of my assignments...

***********************************************************

Add a template to the arrayi.h class so that elements of the arrays can be either integer, float or double.  
Also add a subtraction operator to the class.  

Hint: do one of the above at a time so if there are problems you know which is causing the problem


Write a driver that demonstrates your changes.   Create arrays A1, A2 and A3.  A1 is size 4 with elements 6 7  8  9  A2 is size 7 with elements 1 2 3 4 5 6 7.  Assign A3 the difference of A1 and A2.

***********************************************************

Here is the arrayi.h file...

***********************************************************

//demo cs132  L.Grupka
//arrayi.h
//simple array class

#ifndef ARRAYI_H_
#define ARRAYI_H_

#include <iostream.h>
#include <stdlib.h>
#include <assert.h>
class Array {
      friend ostream &operator<<(ostream &, const Array &);
      friend istream &operator>>(istream &, Array &);

      public:
            Array(int = 10);      //constructor
            Array(const Array &);      //copy constructor
            ~Array();            //destructor
            int getSize() const;      //return size
            Array &operator = (const Array &) ;
            int operator==(const Array &) const;
            int operator != (const Array &) const;
            int &operator[] (int);
            Array operator + (const Array&);
            static int getArrayCount();      //get count of existing
                                    //array objects

      private:
            int *ptr;      //ptr to first array element
            int size;      //size of the array
            static int arrayCount;      // #of arrays instantiated
      };

      #endif

    // ARRAYi.CPP
// Member function definitions for class Array


// Initialize static data member at file scope
int Array::arrayCount = 0;   // no objects yet

// Default constructor for class Array
Array::Array(int arraySize)
{
   ++arrayCount;             // count one more object
   size = arraySize;         // default size is 10
   ptr = new int[size];      // create space for array
   assert(ptr != 0);  // terminate if memory not allocated

   for (int i = 0; i < size; i++)
      ptr[i] = 0;            // initialize array
}

// Copy constructor for class Array
Array::Array(const Array &init)
{
   ++arrayCount;             // count one more object
   size = init.size;         // size this object
   ptr = new int[size];      // create space for array
   assert(ptr != 0);  // terminate if memory not allocated
   cout << "copy constr arrayi " << endl;
   for (int i = 0; i < size; i++)
      ptr[i] = init.ptr[i];  // copy init into object
   cout << endl << "copy constructor working" << endl;
}

// Destructor for class Array
Array::~Array()
{
   --arrayCount;             // one fewer objects
   delete [] ptr;            // reclaim space for array
}

// Get the size of the array
int Array::getSize() const { return size; }

// Overloaded assignment operator
Array &Array::operator=(const Array &right)
{
   if (&right != this) {    // check for self-assignment
      delete [] ptr;        // reclaim space
      size = right.size;    // resize this object
      ptr = new int[size];  // create space for array copy
      assert(ptr != 0);     // terminate if memory not allocated

      for (int i = 0; i < size; i++)
       ptr[i] = right.ptr[i];  // copy array into object
   }
               //this points to ptr to int,  *this returns ptr value
               //ie, the address of the array
   return *this;   // enables x = y = z;
}
// + operator for arrays
Array  Array::operator + (const Array& right)
{      int large, small;
      if (size > right.size)
            {large = size; small = right.size;}
      else
            {large = right.size; small = size;}
      Array z(large);
      for (int i = 0; i < small; i++)
            z.ptr[i] =   ptr[i] + right.ptr[i];
      for (int i = small; i < large; i++)
          { if (right.size == small)
            z.ptr[i] =   ptr[i] ;
            else  z.ptr[i] =   right.ptr[i] ;
          }
       cout << "# of arrays instantiated " << getArrayCount() << endl;
       return z;
}

// Determine if two arrays are equal and
// return 1 if true, 0 if false.
int Array::operator==(const Array &right) const
{
   if (size != right.size)
      return 0;    // arrays of different sizes

   for (int i = 0; i < size; i++)
      if (ptr[i] != right.ptr[i])
       return 0; // arrays are not equal

   return 1;       // arrays are equal
}

// Determine if two arrays are not equal and
// return 1 if true, 0 if false.
int Array::operator!=(const Array &right) const
{
   if (size != right.size)
      return 1;         // arrays of different sizes

   for (int i = 0; i < size; i++)
      if (ptr[i] != right.ptr[i])
       return 1;      // arrays are not equal

   return 0;            // arrays are equal
}

// Overloaded subscript operator
int &Array::operator[](int subscript)
{
   // check for subscript out of range error
   assert(0 <= subscript && subscript < size);
   return ptr[subscript];   // reference return creates lvalue
}

// Return the number of Array objects instantiated
int Array::getArrayCount() { return arrayCount; }

// Overloaded input operator for class Array;
// inputs values for entire array.
istream &operator>>(istream &input, Array &a)
{
   for (int i = 0; i < a.size; i++)
      input >> a.ptr[i];

   return input;   // enables cin >> x >> y;
}

// Overloaded output operator for class Array
ostream &operator<<(ostream &output, const Array &a)
{  int i;
   for (i = 0; i < a.size; i++) {
      output << a.ptr[i] << ' ';

      if ((i + 1) % 10 == 0)
       output << endl;
   }  //end for

   if (i % 10 != 0)
      output << endl;

   return output;   // enables cout << x << y;
}

***********************************************************

Can someone point me in the direction as where to start?  I tried referencing the book to no avail.  Also, I have called/emailed the teacher but she isn't much help.

Ryan
0
Comment
Question by:RySk8er30
  • 7
  • 4
11 Comments
 
LVL 30

Expert Comment

by:Axter
ID: 12123664
The above code is using a type int for the array.
To change the above code to template, just change all the int type to T, and template syntax for the class.
0
 
LVL 30

Accepted Solution

by:
Axter earned 55 total points
ID: 12123682
Example conversion:

class foo
{
   int GetData();
  void SetData(const int& Src);
};

converted version of above class:

template<class T>
clas foo
{
  T GetData();
  void SetData(const T& Src);
};

0
 

Author Comment

by:RySk8er30
ID: 12150145
Hi,

I'm still confused.  I tried that in my code and I am getting a ton of errors...

****************************************************************
//demo cs132  L.Grupka
//arrayi.h
//simple array class

#ifndef ARRAYI_H_
#define ARRAYI_H_

#include <iostream.h>
#include <stdlib.h>
#include <assert.h>

class Array {
      friend ostream &operator<<(ostream &, const Array &);
      friend istream &operator>>(istream &, Array &);

      public:
            Array(int = 10, ArrayType);      //constructor
            Array(const Array &, );      //copy constructor
            ~Array();            //destructor
            int getSize() const;      //return size
            Array &operator = (const Array &) ;
            int operator==(const Array &) const;
            int operator != (const Array &) const;
            int &operator[] (int);
            Array operator + (const Array&);
            Array operator - (const Array&);
            static int getArrayCount();      //get count of existing
                                    //array objects

      private:
            int *ptr;      //ptr to first array element
            int size;      //size of the array
            static int arrayCount;      // #of arrays instantiated
      };

      #endif

    // ARRAYi.CPP
// Member function definitions for class Array


// Initialize static data member at file scope
int Array::arrayCount = 0;   // no objects yet

// Default constructor for class Array
template <class ArrayType>
Array<ArrayType>::Array(int arraySize, ArrayType)
{
   ++arrayCount;             // count one more object
   size = arraySize;         // default size is 10
   ptr = new ArrayType[size];      // create space for array
   assert(ptr != 0);  // terminate if memory not allocated

   for (int i = 0; i < size; i++)
      ptr[i] = 0;            // initialize array
}

// Copy constructor for class Array
template <class ArrayType>
Array<ArrayType>::Array(const Array &init, ArrayType)
{
   ++arrayCount;             // count one more object
   size = init.size;         // size this object
   ptr = new ArrayType[size];      // create space for array
   assert(ptr != 0);  // terminate if memory not allocated
   cout << "copy constr arrayi " << endl;
   for (int i = 0; i < size; i++)
      ptr[i] = init.ptr[i];  // copy init into object
   cout << endl << "copy constructor working" << endl;
}

// Destructor for class Array
Array::~Array()
{
   --arrayCount;             // one fewer objects
   delete [] ptr;            // reclaim space for array
}

// Get the size of the array
int Array::getSize() const { return size; }

// Overloaded assignment operator
Array &Array::operator=(const Array &right)
{
   if (&right != this) {    // check for self-assignment
      delete [] ptr;        // reclaim space
      size = right.size;    // resize this object
      ptr = new int[size];  // create space for array copy
      assert(ptr != 0);     // terminate if memory not allocated

      for (int i = 0; i < size; i++)
       ptr[i] = right.ptr[i];  // copy array into object
   }
               //this points to ptr to int,  *this returns ptr value
               //ie, the address of the array
   return *this;   // enables x = y = z;
}
// + operator for arrays
Array  Array::operator + (const Array& right)
{      int large, small;
      if (size > right.size)
            {large = size; small = right.size;}
      else
            {large = right.size; small = size;}
      Array z(large);
      for (int i = 0; i < small; i++)
            z.ptr[i] =   ptr[i] + right.ptr[i];
      for (i = small; i < large; i++)
          { if (right.size == small)
            z.ptr[i] =   ptr[i] ;
            else  z.ptr[i] =   right.ptr[i] ;
          }
       cout << "# of arrays instantiated " << getArrayCount() << endl;
       return z;
}

// - operator for arrays
Array  Array::operator - (const Array& right)
{      int large, small;
      if (size > right.size)
            {large = size; small = right.size;}
      else
            {large = right.size; small = size;}
      Array z(large);
      for (int i = 0; i < small; i++) {
            
            if (ptr[i] > right.ptr[i]) {
                  z.ptr[i] =   ptr[i] - right.ptr[i];
            } else {
                  z.ptr[i] = right.ptr[i] - ptr[i];
            }

      }
      for (i = small; i < large; i++)
          { if (right.size == small)
            z.ptr[i] =   ptr[i] ;
            else  z.ptr[i] =   right.ptr[i] ;
          }
       cout << "# of arrays instantiated " << getArrayCount() << endl;
       return z;
}

// Determine if two arrays are equal and
// return 1 if true, 0 if false.
int Array::operator==(const Array &right) const
{
   if (size != right.size)
      return 0;    // arrays of different sizes

   for (int i = 0; i < size; i++)
      if (ptr[i] != right.ptr[i])
       return 0; // arrays are not equal

   return 1;       // arrays are equal
}

// Determine if two arrays are not equal and
// return 1 if true, 0 if false.
int Array::operator!=(const Array &right) const
{
   if (size != right.size)
      return 1;         // arrays of different sizes

   for (int i = 0; i < size; i++)
      if (ptr[i] != right.ptr[i])
       return 1;      // arrays are not equal

   return 0;            // arrays are equal
}

// Overloaded subscript operator
int &Array::operator[](int subscript)
{
   // check for subscript out of range error
   assert(0 <= subscript && subscript < size);
   return ptr[subscript];   // reference return creates lvalue
}

// Return the number of Array objects instantiated
int Array::getArrayCount() { return arrayCount; }

// Overloaded input operator for class Array;
// inputs values for entire array.
istream &operator>>(istream &input, Array &a)
{
   for (int i = 0; i < a.size; i++)
      input >> a.ptr[i];

   return input;   // enables cin >> x >> y;
}

// Overloaded output operator for class Array
ostream &operator<<(ostream &output, const Array &a)
{  int i;
   for (i = 0; i < a.size; i++) {
      output << a.ptr[i] << ' ';

      if ((i + 1) % 10 == 0)
       output << endl;
   }  //end for

   if (i % 10 != 0)
      output << endl;

   return output;   // enables cout << x << y;
}
****************************************************************
0
 
LVL 30

Expert Comment

by:Axter
ID: 12152960
Please post the errors you'r getting.
0
 

Author Comment

by:RySk8er30
ID: 12154452
Hey,

I think I understand templates and how to normally use them.  The problem I am having is with the arrays.  In my assignment I need to allow for the array to be a float, int, or double.  How do I do that with templates?  Please look at my above (first post) code and provide an example from there.  Thanks.

Ryan
0
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 

Author Comment

by:RySk8er30
ID: 12155328
Hi,

I think the problem I am having is that the array is created in the constructor and isn't defined in the actual class.  How do I pass that value (whether it is a float, int, double...) from the main program to the constructor in the class?  Please provide an example.  Thanks.

Ryan
0
 
LVL 30

Expert Comment

by:Axter
ID: 12155351
I just looked at the code you posted in your last post, and you did *not* put the template in the class declaration.

Did you look at the example code I posted?
0
 
LVL 30

Expert Comment

by:Axter
ID: 12155353
Look at your code

class Array {
     friend ostream &operator<<(ostream &, const Array &);
     friend istream &operator>>(istream &, Array &);

     public:
          Array(int = 10, ArrayType);     //constructor
          Array(const Array &, );     //copy constructor

There's no template code there.

Now look at the example I posted:

template<class T>
clas foo
{
  T GetData();
  void SetData(const T& Src);
};

Notice the template keyword, with the template logic.
That's what you need to add to your code.
0
 
LVL 30

Expert Comment

by:Axter
ID: 12155357
Example:

template<class T>
class Array {
     friend ostream &operator<<(ostream &, const Array &);
     friend istream &operator>>(istream &, Array &);

     public:
          Array(const T& , ArrayType);     //constructor
          Array(const Array &, );     //copy constructor

Notice that the constructor has a T in it, instead of int

That's how you have to setup your constructor with a template.
0
 
LVL 30

Expert Comment

by:Axter
ID: 12155389
 // ARRAYi.CPP
// Member function definitions for class Array


You can not put the implementation for a template class in the *.cpp file.

You have to put it in the header (*.h) file, and you should put it in the class declaration itself.
Example:
template<class T>
class Array {
     public:
Array(int arraySize)
{
   ++arrayCount;             // count one more object
   size = arraySize;         // default size is 10
   ptr = new T[size];      // create space for array
   assert(ptr != 0);  // terminate if memory not allocated

   for (int i = 0; i < size; i++)
      ptr[i] = 0;            // initialize array
}

Notice that the constructor implementation is inside the class declaration itself, and the the call to new, use T

I've given way more the 50 points worth of data.

And since it's against EE rules to do homework questions, I can not give you much more then this, without you giving feedback with your posted changes, and the errors you recieve.

If you still have errors, please provide proper feedback by posting new code, and posting the exact errors you get.

You can post the errors, by copying and pasting them in the comment block.

0
 

Author Comment

by:RySk8er30
ID: 12163426
Axter,

As always, thanks.

Ryan
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Often, when implementing a feature, you won't know how certain events should be handled at the point where they occur and you'd rather defer to the user of your function or class. For example, a XML parser will extract a tag from the source code, wh…
Introduction This article is a continuation of the C/C++ Visual Studio Express debugger series. Part 1 provided a quick start guide in using the debugger. Part 2 focused on additional topics in breakpoints. As your assignments become a little more …
The viewer will be introduced to the technique of using vectors in C++. The video will cover how to define a vector, store values in the vector and retrieve data from the values stored in the vector.
The viewer will be introduced to the member functions push_back and pop_back of the vector class. The video will teach the difference between the two as well as how to use each one along with its functionality.

932 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

13 Experts available now in Live!

Get 1:1 Help Now