?
Solved

C++ Programming Question

Posted on 2003-03-13
68
Medium Priority
?
371 Views
Last Modified: 2008-03-03
Hi, everyone, I am new to C++ programming. I have an class which is declared as following:

class checked_array {
   public:
          checked_array(int s):size(s){a=new int[size];}
          int &operator[](int i);
          int get_size(0 {return size;}
   private:
          int size;
          int *a;
};

Questions:
1) complete the definition of the checked_array by defining its operator[] method, but placing the definition outside of the class. Be sure that operator[] checks the index is between 0 and size-1. The following is the code I did:

template<class T> //declare the operator method to check if the index is between 0 and size-1.
int &checked_array<T>::operator[](int i) {
     if (i>=0 && i<size)
         return a[i];
     clog << "checked-array::operator[] index out of bounds.\n";
     return *new a;
}

2) convert the checked_array class to a class template. The following is my code:

template<class T>
class checked_array {
public:
     checked_array(int s): size(s) {a=new int[size];}
    int &operator[](int i);
     int get_size() {return size;}
private:
    int size;
     int *a;
};

3) Declare a class template called comparable_checked_array, derived from checked_array, which implements the < operator for comparing two comparable_checked_array's. Given comparable_checked_array's x and y. x<y if the sum of the elements of x is less than the sum of the elements of y.

How can I declare this class template? And what the argument list should be? And How can I call it in the main() procedure? Can anyone give any hints?

Thanks in advance.

0
Comment
Question by:winner21
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 47
  • 19
  • +1
68 Comments
 

Expert Comment

by:blahpers
ID: 8133035
This looks like a homework assignment.  Sorry mate, but I can't write your homework for you.  I'll leave a few tips, though:

When using &&, you (usually) need to separate the expressions with parentheses, as && has a high operator precedence.
Example:
if(a==1 && b==2) {...}  // wrong--equivalent to (a==(1&&b)==2)
if((a==1) && (b==2)) {...} // right

Don't return "new" anything unless that function is specifically supposed to allocate memory.  Otherwise you're asking for a memory leak.

Your template isn't using T anywhere, so it really isn't a template.  Read up on templates in your textbook or consult Google.

Good luck, grasshopper.
0
 
LVL 30

Expert Comment

by:Mayank S
ID: 8134486
template<class T>
class checked_array {

should be:

template<class T>
class checked_array <T> {

Also,

checked_array(int s):size(s){a=new int[size];}

should be:

checked_array(int s) { size = s ; a = new int[size] ; }
0
 
LVL 30

Expert Comment

by:Mayank S
ID: 8134522
int get_size(0 {return size;}

should be:

int get_size() { return size ; }


Also, declare 'size' and 'a' as 'protected' in the base class so that they can be easily accessed here:


template <class T>
class comparable_checked_array : public checked_array ; // not sure if a <T> is reqd
{
  comparable_checked_array () // constructor ()
  {
    ..
    ..

  } // end of constructor ()

  int operator < ( comparable_checked_array & obj ) ;

} ; // class definition over

template <class T>
int comparable_checked_array <T> :: operator < ( comparable_checked_array & obj )
{
  int mysum = 0, othersum = 0, i ;

  for ( i = 0 ; i < size ; i ++ )
    mysum += a[i] ; // end for

  for ( i = 0 ; i < obj.size ; i ++ )
    othersum += obj.a[i] ; // end for

  if ( mysum < othersum )
    return 1 ; // true -> calling object < obj

  return 0 ; // otherwise

} // end of operator < ()

int main ()
{
  comparable_checked_array x, y ;
 
  // read values, etc

  if ( x < y )
    cout << "x is greater. " ; // end if

  return 0 ;

} // end of main ()


Hope that's enough!

Mayank.

[PS: Since you're new to C++, and have still put up a good effort in your example, I have helped you with some code. Next time, please don't ask for complete codes!! Cheers!]
0
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 30

Expert Comment

by:Mayank S
ID: 8134528
Oops! My

comparable_checked_array x, y ;

missed out the data-type <int>, <float>, whatever! Hope you put that!
0
 
LVL 1

Expert Comment

by:fsign21
ID: 8135671
>>convert the checked_array class to a class template.
I think, this should be

class OutOfRange {};

template<class T>
class checked_array {
public:
   checked_array(unsigned int s)
       : size(s) {a=new T[size];}
   //do not forget the destructor
   virtual ~checked_array() { delete [] a; }

   T& operator[](unsigned int i);
   unsigned int get_size() const {return size;}

private:
   uint size;
   T *a;
};

template<class T>
T& checked_array<T>::operator[](int i) {
    if (i>=size) {
    clog << "checked-array::operator[] index out of bounds.\n";
    throw OutOfRange();
    }
    return a[i];
}
0
 
LVL 1

Author Comment

by:winner21
ID: 8137701
Thanks for everyone's input. I really apprecaite it. These codes give me more sense about C++. However, there are still a couple questions:

1. To Mayank: When I make new instance for the comprable_checked_array in main(), I always got error message which says "cannot access private member declared in class 'comparable_checked_array<int>". It seems this is a variable scope problem. Should I change the mysum and othersum to public variables.

2. In order to improve my skills, I added a sort template function, the following is my code:

template<class T, class ELT> //template function for sort, the first parameter is for checked_array and the latter one is for comparable_checked_array
void sort(T &a, int size) //we change int to T ensure other data type will be accepted
{
 ELT temp;
 for (int i=size-1; i>=0; i--)
      for (int j=0;j<i;j++)
           if (a[j+1]<a[j]) {
                temp=a[j+1];
                a[j+1]=a[j];
                a[j]=temp;
           }
}

the parameter T refers to checked_array and ELT refers to comparable_checked_array. When I try to call this function by using sort(sort(A,9),sort(B,9)) where A and B are two arrays, why this don't work?

Thanks again.
0
 
LVL 30

Expert Comment

by:Mayank S
ID: 8142921
>> Should I change the mysum and othersum to public variables.

I don't think so. They are not being accessed in main ().

>> When I try to call this function by using sort(sort(A,9),sort(B,9)) where A and B are two arrays, why this don't work?

I think I'll be able to help you better if you can post your entire code here (if that's not a problem), and also point out what errors you are getting and where.

Mayank.
0
 
LVL 1

Author Comment

by:winner21
ID: 8144004
To Mayank: Thank you very much for your help. The following is the entire cpp file. I know the main() is still under construction.

#include <iostream.h>

template<class T>
class checked_array {
public:
     checked_array(int s): size(s) {a=new int[size];}
    int &operator[](int i);
     int get_size() {return size;}
protected:
    int size;
     int *a;
};

class OutOfRange{};

template<class T> //declare the operator method to check if the index is between 0 and size-1.
int &checked_array<T>::operator[](int i) {
     if ((i>=0) && (i<size))
         return a[i];
     clog << "checked-array::operator[] index out of bounds.\n";
     throw OutOfRange();
}

template<class ELT>
class comparable_checked_array:public checked_array<ELT>{ //comparable_checked_array is derived from checked_array
     comparable_checked_array(); // constructor()
     int operator<(comparable_checked_array & obj);
};

template<class ELT>
int comparable_checked_array<ELT>::operator<(comparable_checked_array & obj)
{
public:
     int mysum=0, othersum=0;
     for(i=0;i<size;i++)
          mysum+=a[i];     //end for
     for(i=0;i<obj.size;i++)
          othersum+=obj.a[i]; //end for
    if (mysum<othersum)
          return 1; //true
     return 0;//otherwise
protected:
     int i;
} //end of operator < 


template<class T, class ELT> //template function for sort, the first parameter is for checked_array and the latter one is for comparable_checked_array
void sort(T &a, int size) //we change int to T ensure other data type will be accepted
{
 ELT temp;
 for (int i=size-1; i>=0; i--)
      for (int j=0;j<i;j++)
           if (a[j+1]<a[j]) {
                temp=a[j+1];
                a[j+1]=a[j];
                a[j]=temp;
           }
}

void main()
{    
     comparable_checked_array<int> x;
     int x[3]={4,3,5};
     //print the array value before sorting
     //sort x and y
     // 1) first sort all elements in array itself
     // 2) sort array x and y
     sort(sort(x,3),sort(y,3));
     


}
0
 
LVL 1

Author Comment

by:winner21
ID: 8144018
To Mayank: Thank you very much for your help. The following is the entire cpp file. I know the main() is still under construction.

#include <iostream.h>

template<class T>
class checked_array {
public:
     checked_array(int s): size(s) {a=new int[size];}
    int &operator[](int i);
     int get_size() {return size;}
protected:
    int size;
     int *a;
};

class OutOfRange{};

template<class T> //declare the operator method to check if the index is between 0 and size-1.
int &checked_array<T>::operator[](int i) {
     if ((i>=0) && (i<size))
         return a[i];
     clog << "checked-array::operator[] index out of bounds.\n";
     throw OutOfRange();
}

template<class ELT>
class comparable_checked_array:public checked_array<ELT>{ //comparable_checked_array is derived from checked_array
     comparable_checked_array(); // constructor()
     int operator<(comparable_checked_array & obj);
};

template<class ELT>
int comparable_checked_array<ELT>::operator<(comparable_checked_array & obj)
{
public:
     int mysum=0, othersum=0;
     for(i=0;i<size;i++)
          mysum+=a[i];     //end for
     for(i=0;i<obj.size;i++)
          othersum+=obj.a[i]; //end for
    if (mysum<othersum)
          return 1; //true
     return 0;//otherwise
protected:
     int i;
} //end of operator < 


template<class T, class ELT> //template function for sort, the first parameter is for checked_array and the latter one is for comparable_checked_array
void sort(T &a, int size) //we change int to T ensure other data type will be accepted
{
 ELT temp;
 for (int i=size-1; i>=0; i--)
      for (int j=0;j<i;j++)
           if (a[j+1]<a[j]) {
                temp=a[j+1];
                a[j+1]=a[j];
                a[j]=temp;
           }
}

void main()
{    
     comparable_checked_array<int> x;
     int x[3]={4,3,5};
     //print the array value before sorting
     //sort x and y
     // 1) first sort all elements in array itself
     // 2) sort array x and y
     sort(sort(x,3),sort(y,3));
     


}
0
 
LVL 30

Expert Comment

by:Mayank S
ID: 8146086
sort () is a function which takes a template class object and an integer as arguments and returns nothing. So, sort ( x, 3 ) is valid and sort ( y, 3 ) is valid. But sort ( sort ( x, 3 ), sort ( y, 3 ) ) effectively turns out to be of the form sort ( void, void ) since the sort () function calls inside return nothing. You don't need to write sort ( sort ( x, 3 ), sort ( y, 3 ) ) ; Just change it to:

sort ( x, 3 ) ;
sort ( y, 3 ) ;

// if needed -

if ( x < y )
  cout << "x is lesser. " ; // end if

Hope that helps!

Mayank.
0
 
LVL 1

Author Comment

by:winner21
ID: 8148987
thanks, Mayank. However, did you see the sort is a template function which has two parameters - the first one is the checked_array and the second one is the comparable_checked_array. Do you think there is no affection for these two parameters? Thanks,
0
 
LVL 30

Expert Comment

by:Mayank S
ID: 8149327
Since you're comparing 2 comparable_array objects (and passing them only), I think that you can change it to:

template <class ELT>
void sort ( ELT &a, int size )
{
  ELT temp ;
  for ( int i = size - 1 ; i >= 0 ; i -- )
     for ( int j = 0 ; j < i ; j ++ )
       if ( a[j+1] < a[j] )
       {
         temp = a[j+1] ;
         a[j+1] = a[j] ;
         a[j] = temp ;

       } // end if, fors

} // end of sort ()


Mayank.

0
 
LVL 1

Author Comment

by:winner21
ID: 8151858
Hi Mayank, are you sure the sort template function is correct? Why did you only declare it as a ELT class?
0
 
LVL 30

Expert Comment

by:Mayank S
ID: 8152019
Since you're passing only one type of template class object to it (and the other argument is always an integer), you don't need to put both ELT and T into its declaration. In fact, if you can make it:

template <class T>
void sort ( T &a, int size )
{
 T temp ;

 for ( int i = size - 1 ; i >= 0 ; i -- )
    for ( int j = 0 ; j < i ; j ++ )
      if ( a[j+1] < a[j] )
      {
        temp = a[j+1] ;
        a[j+1] = a[j] ;
        a[j] = temp ;

      } // end if, fors

} // end of sort ()


I haven't checked the logic of your sorting function, just modified the first line a little-bit.

Please let me know if there are any problems.

Mayank.
0
 
LVL 1

Author Comment

by:winner21
ID: 8152092
Thanks again, Mayank. I think you are correct with the sort template function. However, what if I have to put the checked_array and comparable_checked_array together as the sort arugment lists, how can I call them? This q comes back to my original question, which is sort(sort(A,5), sort(B,5)). If you look at the following definition and requirement, you might know why I am so stubborn to use this way...

**********************************************************
Consider the following definition of a C++ class that acts like an array with bounds-checking (i.e. ensuring that a valid array index is used each time an array element is referenced).

class checked_array {
  public:
     checked_array(int s): size(s) { a = new int[size]; }
     int &operator[](int i);
     int get_size() { return size; }
  protected:
     int size;
     int *a;
};

1)     Complete the definition of the checked_array class by defining its operator[] method, but placing the definition outside of the class. Be sure that operator[] checks that the index is between 0 and size - 1.
2)     Convert the checked_array class to a class template, where the type of the elements of the array is a template parameter.
3)     Declare a class template called comparable_checked_array, derived from checked_array, which implements the < operator for comparing two comparable_checked_array's. Given comparable_checked_array's X and Y, X < Y if the sum of the elements of X is less than the sum of the elements of Y.
4)     The following is the code for a C++ function sort() for sorting arrays of integers.

void sort(int a[], int size)
{
  int temp;
  for (int i = size - 1; i >= 0; i--)
    for (int j = 0; j < i; j++)
       if (a[j+1] < a[j]) {
         temp = a[j+1];
         a[j+1] = a[j];
         a[j] = temp;
         }
}

 Convert this function to a template function that can be used to sort an array of any type supporting the < operator. Test your template function by sorting an array of floats.

5) Finally, create a checked_array A containing elements that are themselves comparable_checked_array's of integers. Then, use your sort template to,
•     for each element x of A, sort the elements of x, and
•     sort A itself.

For example, if A is a checked_array of comparable_checked_array's such that:
  A[0] = {2,4,1}
  A[1] = {5,3,7}
  A[2] = {0,3,2}

then after all the sorting, A will look like:
  A[0] = {0,2,3}
  A[1] = {1,2,4}
  A[2] = {3,5,7}
**********************************************************

Thank you very much.

 

0
 
LVL 30

Expert Comment

by:Mayank S
ID: 8152187
Hi winner,

Your questions will need explanations - I have all of them but I'm leaving for the day (its almost 9:00 PM IST).

I will give you the answer tomorrow.

Please just post a small message on this page so that I get reminded of it when I check my mail tomorrow.

Mayank.
0
 
LVL 1

Author Comment

by:winner21
ID: 8152215
Thank you, Mayank. I will give you a reminder. Have a good day.
0
 
LVL 1

Author Comment

by:winner21
ID: 8152674
Mayank,

Just a reminder to you - I did not put anything under the constructor comparable_checked_array(). Do you think this will cause any issues? And also could you explain what is operator<(comparable_checked_array & obj)?
0
 
LVL 30

Expert Comment

by:Mayank S
ID: 8156878
Ok, so what you need to do is:

1. Declare an array of objects of type comparable_checked_array

2. Overload the operator < to check if obj1 < obj2, where obj1 and obj2 are two objects of the comparable_checked_array class

3. Sort the array using the overloaded operator

Now, the answers to some other questions of yours:

>> I did not put anything under the constructor comparable_checked_array().

First of all, modify the checked_array class member a as:

T * a ;

otherwise there is no use of the class template. Now you can dynamically declare objects of this class which will hold different types of values based on what data-type T wil specify:

checked_array <int> obj1 ( 4 ); // int type array of size 4 will be made
checked_array <float> obj2 ( 5 ) ; // float type array of size 5 will be made

That is the advantage of having class template. Now, since you will be declaring objects not of the checked_array class, but of the comparable_checked_array class, modify the constructor of comparable_checked_array definition as:

comparable_cheked_array ( int s )
{
  checked_array ( s ) ;

} // end of constructor ()

Now, when you declare an object of comparable_checked_array, then this constuctor will be called and this will call the checked_array constructor, which will allocate the memory for the array 'a', and also initialize 'size'.

>> sort(sort(A,5), sort(B,5))

That is wrong syntax. Actually, a function call is always replaced by its return value and so, here, sort ( A, 5 ) and sort ( B, 5 ) will return nothing, and the call becomes like:

sort ( void, void )

which is invalid. If you want to sort the individual elements in A, B, and so on, then you need to write a function which will sort individual elements in the 'a' array of an object of the comparable_checked_array class, like:

void sort () // make it a data-member of the comparable_checked_array class
{
T temp ;

for ( int i = size - 1 ; i >= 0 ; i -- )
   for ( int j = 0 ; j < i ; j ++ )
     if ( a[j+1] < a[j] )
     {
       temp = a[j+1] ;
       a[j+1] = a[j] ;
       a[j] = temp ;

     } // end if, fors

} // end of sort ()

>> what if I have to put the checked_array and comparable_checked_array together as the sort arugment lists

Don't do it. Its not needed. The function above will sort the individual comparable_checked_array objects.

>> what is operator<(comparable_checked_array & obj)

Then, you need to write another function which will sort an entire array of comparable_checked_array objects. This function will be different from the one above because there, we'll be comparing two entire objects in the if statement, not two numbers as above. Since the < operator cannot compare 2 objects, so we will have to overload the < operator and tell it what to do if it comes across 2 object arguments. That is what the above 'operator < (comparable_checked_array & obj)' is. It is supposed to be a function which will define how the < operator should behave when it comes across two comparable_checked_array objects (notice that only one object obj is mentioned here - that is the second argument, and the first argument will be implicit -> the object which will call this function (if you make this function a member of the class)).

Like:

class comparable_checked_array ....
{
....

  int operator < ( comparable_checked_array & obj ) ;

// function which will define how the operator < should behave when invoked by object of the class, and return an integer

} ;

....
....

// x and y are comparable_checked_array objects

if ( x < y )

// here - x is the implicit object, and y is passed by reference to obj, got it? This is treated like a call to a member function of x as:

x.operator < ( y )  

where operator < () is the function, and y is passed as an argument (by reference) to obj.

>> x<y if the sum of the elements of x is less than the sum of the elements of y.

Ok, then the function definition is:

class comparable_checked_array ....
{
....

  int operator < ( comparable_checked_array & obj )
  {
    int mysum = 0, othersum = 0, i ;

     for ( i = 0 ; i < size ; i ++ )
       mysum += a[i] ; // end for

     for ( i = 0 ; i < obj.size ; i ++ )
       othersum += obj.a[i] ; // end for

     if ( mysum < othersum )
       return 1 ; // true -> calling object < obj

     return 0 ; // otherwise

  } // end of operator < ()

} ;

This will return 1 if x < y, else return 0.

Now, if you have an array of comparable_checked_array objects like:

comparable_checked_array <int> A[10] ;

Here, all these obj[i], 0 <= i < 10, are objects like x and y. So, you can perform obj[i] < obj[j] for some i and j. That is what will help you in sorting the array. Let's write a function for that as:

template <class T>
void sort_obj_array ( comparable_checked_array <T> A[], int n ) // make it a friend of the comparable_checked_array class
{
comparable_checked_array <T> temp ;

for ( int i = size - 1 ; i >= 0 ; i -- )
   for ( int j = 0 ; j < i ; j ++ )
     if ( A[j+1] < A[j] )
     {
       temp = A[j+1] ;
       A[j+1] = A[j] ;
       A[j] = temp ;

     } // end if, fors

} // end of sort ()

Call it as:

sort_obj_array ( A, 10 ) ;


Hope that much helps!

Mayank.
0
 
LVL 1

Author Comment

by:winner21
ID: 8163530
Hi, Mayank, Thank you for your help. I really appreciate. However, I still have a couple of questions which I feel not very clear.

1. I understand why you declare two different sort function, however, is there any way to merge these two sort functions together? In this case, I think the sort() function should hold two objects as parametes - class T and another class T', which are referred to Checked_array and Comparable_checked_array. Such as

template<Class T, Class T'>
void sort(T &a, int i){...}

Is this correct? How can I call it?

2. When I make an new instance in main() as of comparable_checked_array<int> A[10]; I always get the following error message: "error C2512: 'comparable_checked_array<int>' : no appropriate default constructor available". However, If I change it to comparable_checked_array<int> A();, which is fine, at least no error. But why?

3. The orginal question requires me to create a checked_array A containing elements that are themseleves comparable_checked_array's of integers. According to this, I declated an array A as following:

void main(){
   checked_array<int> A(3);
   //THEN I need to initialize the array with elements.
   I did as A[0]={1,4,2}, A[1]={5,3,4}; However, I got    error. So, how shall I initialize the array? And is it possible to initialize the array with elements such as A[0]={1,4,2}, where I understand the A[0] is the first element of the array, but why we can set it to 3 elements? If we can do this, how can we call the sort function?
   comparable_checked_array<int> B[10]; //I got error for this.
...
}

Sorry for bothering you again, however these qs always come up when I do this code.

Thanks again in advance.


0
 
LVL 1

Author Comment

by:winner21
ID: 8163538
Hi, Mayank, Thank you for your help. I really appreciate. However, I still have a couple of questions which I feel not very clear.

1. I understand why you declare two different sort function, however, is there any way to merge these two sort functions together? In this case, I think the sort() function should hold two objects as parametes - class T and another class T', which are referred to Checked_array and Comparable_checked_array. Such as

template<Class T, Class T'>
void sort(T &a, int i){...}

Is this correct? How can I call it?

2. When I make an new instance in main() as of comparable_checked_array<int> A[10]; I always get the following error message: "error C2512: 'comparable_checked_array<int>' : no appropriate default constructor available". However, If I change it to comparable_checked_array<int> A();, which is fine, at least no error. But why?

3. The orginal question requires me to create a checked_array A containing elements that are themseleves comparable_checked_array's of integers. According to this, I declated an array A as following:

void main(){
   checked_array<int> A(3);
   //THEN I need to initialize the array with elements.
   I did as A[0]={1,4,2}, A[1]={5,3,4}; However, I got    error. So, how shall I initialize the array? And is it possible to initialize the array with elements such as A[0]={1,4,2}, where I understand the A[0] is the first element of the array, but why we can set it to 3 elements? If we can do this, how can we call the sort function?
   comparable_checked_array<int> B[10]; //I got error for this.
...
}

Sorry for bothering you again, however these qs always come up when I do this code.

Thanks again in advance.


0
 
LVL 1

Author Comment

by:winner21
ID: 8163576
To Mayank: For your reference, I attached all the code here:

====================================================================================================================
#include <iostream.h>

template<class T>
class checked_array {
public:
     checked_array(int s): size(s) {a=new int[size];}
    int &operator[](int i);
     int get_size() {return size;}
protected:
    int size;
     T *a;
};

class OutOfRange{};

template<class T> //declare the operator method to check if the index is between 0 and size-1.
int &checked_array<T>::operator[](int i) {
     if ((i>=0) && (i<size))
         return a[i];
     clog << "checked-array::operator[] index out of bounds.\n";
     throw OutOfRange();
}

template<class T>
class comparable_checked_array:public checked_array<T>{ //comparable_checked_array is derived from checked_array
     comparable_checked_array(int s) {
    checked_array(s);
     }
     int operator<(comparable_checked_array & obj);
};

template<class T>
int comparable_checked_array<T>::operator<(comparable_checked_array & obj)
{
     int mysum=0, othersum=0;
     for(int i=0;i<size;i++)
          mysum+=a[i];     //end for
     for(int i=0;i<obj.size;i++)
          othersum+=obj.a[i]; //end for
    if (mysum<othersum)
          return 1; //true
     return 0;//otherwise
} //end of operator < 


template<class T> //template function for sort, the first parameter is for checked_array and the latter one is for comparable_checked_array
void sort(T &a, int size) //we change int to T ensure other data type will be accepted
{
 T temp;
 for (int i=size-1; i>=0; i--)
      for (int j=0;j<i;j++)
           if (a[j+1]<a[j]) {
                temp=a[j+1];
                a[j+1]=a[j];
                a[j]=temp;
           }
}

template<class T>
void sort_obj_array(comparable_checked_array<T> A[], int n) //make it a friend of the comparable_checked_array
{
     comparable_checked_array <T> temp;
     for (int i=size-1; i>=0; i--)
    for (int j=0;j<i;j++)
           if (A[j+1]<A[j]) {
                temp=A[j+1];
                A[j+1]=A[j];
                A[j]=temp;
           }
}
void main()
{    
//comments: create a checked_array A containing elements that are themselves comparable_checked_array's of integers.
     checked_array<int> A(3);
     comparable_checked_array<int> B[10];
    //initialize elements for array A.
     int A[0]={1,4,3};
     int A[1]={4,5,3};
     int A[2]={3,5,7};
     //print all elemts in array A.
     for(int i=0;i<3;i++)
          cout << "Array A has elements: " << A[i] << endl;
     //sort all elements in array A.
     sort(A,3);
     //print all elements in array after sorting,
     for(int i=0;i<3;i++)
          cout << "Array A has elements: " << A[i] << endl;
     //sort checked_array A itself and print the results.
     //no idea with this.


}
0
 
LVL 30

Expert Comment

by:Mayank S
ID: 8164269
>>  there any way to merge these two sort functions together?

Its better not to merge because the function which sorts the individual arrays in each object will be called as many times as there are objects, but the function which sorts the entire 'array of objects' will be called only once. Also, since you're not instantiating the checked_array class anywhere, you need not use a 'T' parameter for it. You can only use one - for the comparable_checked_array object which you will be passing to it.

However, you might do one thing: You might write the sort () function such that it is called only once and it first sorts all the elements in each object, and then sorts the entire array of objects, as:

class comparable_checked_array ....
{
....

 int operator < ( comparable_checked_array & obj )
 {
   int mysum = 0, othersum = 0, i ;

    for ( i = 0 ; i < size ; i ++ )
      mysum += a[i] ; // end for

    for ( i = 0 ; i < obj.size ; i ++ )
      othersum += obj.a[i] ; // end for

    if ( mysum < othersum )
      return 1 ; // true -> calling object < obj

    return 0 ; // otherwise

 } // end of operator < ()

} ; // class definition over

template <class T>
void sort_obj_array ( comparable_checked_array <T> A[], int n ) // make it a friend of the comparable_checked_array class
{
comparable_checked_array <T> x ;
T temp ;

for ( int k = 0 ; k < n ; k ++ )
for ( int i = A[k].size - 1 ; i >= 0 ; i -- )
  for ( int j = 0 ; j < i ; j ++ )
    if ( A[k].a[j+1] < A[k].a[j] )
    {
      temp = A[k].a[j+1] ;
      A[k].a[j+1] = A[k].a[j] ;
      A[k].a[j] = temp ;

    } // end if, fors

} // end of sort ()

for ( int i = n - 1 ; i >= 0 ; i -- )
  for ( int j = 0 ; j < i ; j ++ )
    if ( A[j+1] < A[j] )
    {
      x = A[j+1] ;
      A[j+1] = A[j] ;
      A[j] = x ;

    } // end if, fors

} // end of sort ()

Call it as:

sort_obj_array ( A, 10 ) ;


>> no appropriate default constructor available

Apart from the parameterized constructor that you have for the comparable_checked_array class, also give a default construtor with no arguments which will set the size to some value and initialize the array data-member's elements with some values.

>> A[0]={1,4,2}

No. A[] is not an integer array or a floating-point array, so it cannot be initialized this way. The easiest way to initialize the array elements would be to write a function for it:

void init ( T b[], int n ) // member function of checked_array
{
  size = n ;
  a = new int[size] ;

  for ( int i = 0 ; i < n ; i ++ )
    a[i] = b[i] ; // end for

} // end of init ()

And for each object in your array of objects, call the init () function, passing some integer/ floating-point (whatever - based on your need) array defined in main () and its range as the argument.

Hope that helps!

Mayank.
0
 
LVL 1

Author Comment

by:winner21
ID: 8171612
Hi Mayank, I got your code and completely I can understand what you described in your notes. However, when I try to make it in C++ develop environment, I always feel I lost the way. I have almost finished the code and you can see the following is one copy of the entire code, if you don't mind, could you check it again for me and also fill in those missed part in main(). I hate to do this, however, I think I am at the edge of the door, sometimes I have idea, sometimes I totally lost. C++ seems very tricky for me.

**********************************************************
#include <iostream.h>

// stdafx.h : include file for standard system include files,
//  or project specific include files that are used frequently, but
//      are changed infrequently
//

#if !defined(AFX_STDAFX_H__3BB39F4C_DBB5_4365_BF47_EC5522D1C2BB__INCLUDED_)
#define AFX_STDAFX_H__3BB39F4C_DBB5_4365_BF47_EC5522D1C2BB__INCLUDED_

#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000

#include <stdio.h>
#include <stdlib.h>
// TODO: refere.hnce additional headers your program requires here

//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.

#endif // !defined(AFX_STDAFX_H__3BB39F4C_DBB5_4365_BF47_EC5522D1C2BB__INCLUDED_)


template<class T>
class checked_array {
public:
      checked_array(int s): size(s) {a=new int[size];}
    int &operator[](int i);
      int get_size() {return size;}
protected:
    int size;
      T *a;
};

class OutOfRange{};

template<class T> //declare the operator method to check if the index is between 0 and size-1.
int &checked_array<T>::operator[](int i) {
      if ((i>=0) && (i<size))
          return a[i];
      clog << "checked-array::operator[] index out of bounds.\n";
      throw OutOfRange();
}

template<class T>
class comparable_checked_array:public checked_array<T>{ //comparable_checked_array is derived from checked_array
      //put some constructor here

      comparable_checked_array(int s) {
    checked_array(s);
      }
      int operator<(comparable_checked_array & obj);
};

template<class T>
int comparable_checked_array<T>::operator<(comparable_checked_array & obj)
{
      int mysum=0, othersum=0;
      for(int i=0;i<size;i++)
            mysum+=a[i];     //end for
      for(int i=0;i<obj.size;i++)
            othersum+=obj.a[i]; //end for
    if (mysum<othersum)
            return 1; //true
      return 0;//otherwise
} //end of operator < 


//template<class T> //template function for sort, the first parameter is for checked_array and the latter one is for comparable_checked_array
//void sort(T &a, int size) //we change int to T ensure other data type will be accepted
//{
// T temp;
// for (int i=size-1; i>=0; i--)
//       for (int j=0;j<i;j++)
//             if (a[j+1]<a[j]) {
//                   temp=a[j+1];
//                   a[j+1]=a[j];
//                   a[j]=temp;
//             }
//}

template<class T>
void sort_obj_array(comparable_checked_array<T> A[], int n) //make it a friend of the comparable_checked_array
{
      comparable_checked_array <T> x;
      T temp;
      for(int k=0;k<n;k++)
      for(int i=A[k].size-1; i>=0; i--)
    for (int j=0;j<i;j++)
             if (A[k].a[j+1]<A[k].a[j]) {
                   temp=A[k].a[j+1];
                   A[k].a[j+1]=A[k].a[j];
                   A[k].a[j]=temp;
             }
   
      for (int i=n-1; i>=0; i--)
      for (int j=0;j<i;j++)
             if (A[j+1]<A[j]) {
                   x=A[j+1];
                   A[j+1]=A[j];
                   A[j]=x;
             }

}//end of sort



void main()
{      
//comments: create a checked_array A containing elements that are themselves comparable_checked_array's of integers.
    int nCols,nRows; //nCols and nRows represent the columns and rows in an array, respectively.
      int nElem;
      int inp;
      inp=10;
      char bBuf[20];
          
      puts("Define number of columns in Array");
      gets(bBuf);
      nCols = atoi(bBuf);
      puts("Define number of rows in Array");
      gets(bBuf);
      nRows = atoi(bBuf);
      nElem = nCols*nRows;
   
      //now let's declare an checked_array A and initialize its size;
    checked_array<int> A(nElem);
   
    printf("You have defined Array A with %d columns and %d rows\n",nCols,nRows);
      printf("Totally with %d elements\n",nElem);
      printf("Now input %d elements of Array\n",nElem);
      puts("To interrupt sequens input 0");
      for(int ii=0;ii<nElem;ii++)
            {
                  if (ii%nCols == 0)
                        puts("");
                  gets(bBuf);
                  inp = atoi(bBuf);
            //add all elements to the array A.

                           
           
            }
      
        //print all elements in array A.
          

          //sort array A and print all elements in this array. From my understanding, which is we should sort the rows.

          

          


}
*********************************************************
Thank you very much.

By the way, my personal email address is MT5188@aol.com, if you can wrap the code and send it back to the above email, that will be greatest help for me.

0
 
LVL 30

Expert Comment

by:Mayank S
ID: 8171713
Hi Winner,

Actually, my version of C++ is very old, and it doesn't recognize class templates!

However, I will work on your code and send it you.... I need some more time. You might have to compile it and tell me if you got any errors, because I won't be able to compile it on my system.

Mayank.
0
 
LVL 1

Author Comment

by:winner21
ID: 8175391
thank you, Mayank. I will try to compile my code and send all your error details. Thanks again.
0
 
LVL 1

Author Comment

by:winner21
ID: 8184258
Mayank, I would not think we need any changes for the code except the main(), which I got errors when I tried to call those declared template class and function. And also still I am not very clear with the initialization with the array, such as A[0]={1,2,3}. From my understanding, this should be equal to A[0][0]=1, A[0][1]=2 and A[0][2]=3, in other words, this array holds 3 columns and 1 row. If I declare an array such as A[3], according to above example, this should be 3x3 array. Is this correct?
0
 
LVL 1

Author Comment

by:winner21
ID: 8185446
hi, Manyank, sorry to bother you - I still have the question how to declare the checked_array A which contains elements that are all comparable_checked_array, could u give me some example? thks.
0
 
LVL 30

Expert Comment

by:Mayank S
ID: 8185649
You cannot initialize the array A[] as:

A[0] = { 1, 2, 3 }

etc., because A[] is not a normal integer or floating-point array but an array of objects. You might have to initialize it in the constructor or by using some other member function to initialize the values.

>> how to declare the checked_array A

A[] can be declared as comparable_checked_array and I think that's a better way of doing it.

Please keep this page updated.

Mayank.
 
0
 
LVL 1

Author Comment

by:winner21
ID: 8188026
hi, Mayank, what's going on with you? Can you finish it before Tuesday? I am eager to see the correct code. Thanks. The following is the entire code for this assignment:

**********************************************************
#include <iostream.h>

template<class T>
class checked_array {
public:
     checked_array(int s): size(s) {a=new int[size];}
    int &operator[](int i);
     int get_size() {return size;}
protected:
    int size;
     T *a;
};

class OutOfRange{};

template<class T> //declare the operator method to check if the index is between 0 and size-1.
int &checked_array<T>::operator[](int i) {
     if ((i>=0) && (i<size))
         return a[i];
     clog << "checked-array::operator[] index out of bounds.\n";
     throw OutOfRange();
}

template<class T>
class comparable_checked_array:public checked_array<T>{ //comparable_checked_array is derived from checked_array
     comparable_checked_array(int s);
     int operator<(comparable_checked_array & obj);
};

template<class T>
int comparable_checked_array<T>::operator<(comparable_checked_array & obj)
{
     int mysum=0, othersum=0;
     for(int i=0;i<size;i++)
          mysum+=a[i];     //end for
     for(int i=0;i<obj.size;i++)
          othersum+=obj.a[i]; //end for
    if (mysum<othersum)
          return 1; //true
     return 0;//otherwise
}

template<class T> //template function for sort, the first parameter is for checked_array and the latter one is for comparable_checked_array
void sort(T a[], int size) //we change int to T ensure other data type will be accepted
{
 T temp;
 for (int i=size-1; i>=0; i--)
      for (int j=0;j<i;j++)
           if (a[j+1]<a[j]) {
                temp=a[j+1];
                a[j+1]=a[j];
                a[j]=temp;
           }
}

void main()
{    
 //create a checked_array A containing elements that are themselves comparale_checked_array's of integers.

     checked_array<int> A(3);
         
    int A1[]={2,4,1};
     int A2[]={5,3,7};
     int A3[]={0,3,2};

     cout << "Checked Array A has three elements that are comparable checked array: A1, A2, A3." << endl;
    cout << "comparable checked array A1 has elements: " << A1[0] << "," << A1[1] << "," << A1[2] << endl;
    cout << "comparable checked array A2 has elements: " << A2[0] << "," << A2[1] << "," << A2[2] << endl;
     cout << "comparable checked array A3 has elements: " << A3[0] << "," << A3[1] << "," << A3[2] << endl;

     sort<int>(A1,3);
     cout << "After sorting, comparable checked array A1 has elements in order as of: " << A1[0] << "," << A1[1] << "," << A1[2] << endl;
    sort<int>(A2,3);
     cout << "After sorting, comparable checked array A2 has elements in order as of: " << A2[0] << "," << A2[1] << "," << A2[2] << endl;
    sort<int>(A3,3);
     cout << "After sorting, comparable checked array A3 has elements in order as of: " << A3[0] << "," << A3[1] << "," << A3[2] << endl;

}
**********************************************************

The above code only works for primitive type, somehow, if you look at my main(), I declared an array A which is a checked_array with elements 3, however, I don't know how to set its 3 elements as comparable_checked_array, and this blocks me to get into next step. Any hints?

Thanks,












0
 
LVL 30

Expert Comment

by:Mayank S
ID: 8189524
>> sort<int>(A1,3);

You don't need to call it this way. You need to write:

sort ( A1, 3 ) ;

but even that's wrong because sort () is not defined for 'int's, but for objects.

And you have declared A1, etc to be 'int' arrays, so all the class definitions, etc don't have any use at all. The whole purpose of the program is lost there. And now, I see that you need A[] to be a checked_array.

I will get back to you on Monday.... am a little occupied right now.

Please keep this page updated.

Mayank.
0
 
LVL 1

Author Comment

by:winner21
ID: 8190300
Yes, Mayank, you are right, Actually I know this, and the reason I declared A1 and A2 and A3 here as integer is just give me some example, however this is not the correct and original purpose of this program.
0
 
LVL 30

Accepted Solution

by:
Mayank S earned 80 total points
ID: 8192899
/* Hi, Winner. Try this: */

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

template <class T>
class checked_array
{
protected:
      int size ;
      T * a ;
public:
      checked_array () // default constructor ()
      {
            size = 0 ;
            a = NULL ;

      } // end of default constructor ()

      checked_array ( int s ) // parameterized constructor ()
      {
             size = s ;
            a = new T[size] ;

      } // end of parameterized constructor ()

      void init ( T [], int ) ;

      T & operator [] ( int ) ;
      
      int get_size ()
      {
            return size ;

      } // end of get_size ()

} ; // class definition over

class OutOfRange {} ;

template <class T>
T & checked_array <T> :: operator [] ( int i )
{
      if ( ( i >= 0 ) && ( i < size ) )
            return a[i] ; // end if

      clog << "Checked-array :: operator [] index out of bounds. " << endl ;
      throw OutOfRange () ;

} // end of operator []

template <class T>
void checked_array <T> :: init ( T b[], int n )
{
      size = n ;
      a = new T[size] ;

      for ( int i = 0 ; i < size ; i ++ )
            a[i] = b[i] ; // end for

} // end of init ()

template <class T>
class comparable_checked_array : public checked_array <T>
{
      comparable_checked_array () : checked_array () // default constructor ()
      {

      } // end of default constuctor ()

      comparable_checked_array ( int s ) : checked_array ( s ) // parameterized constructor ()
      {

      } // end of parameterized constructor ()

      int operator < ( comparable_checked_array & ) ;
      friend void sort_obj_array ( T [], int ) ;

} ; // class definition over

template<class T>
int comparable_checked_array <T> :: operator < ( comparable_checked_array & obj )
{
      int mysum = 0, othersum = 0 ;

      for ( int i = 0 ; i < size ; i ++ )
            mysum += a[i] ; //end for
     
      for ( int i = 0 ; i < obj.size ; i ++ )
            othersum += obj.a[i] ; //end for

      if ( mysum < othersum )
            return 1; // true

      return 0 ; // otherwise

} //end of operator < ()

template<class T>
void sort_obj_array ( checked_array <T> A[], int n ) //make it a friend of the comparable_checked_array
{
      comparable_checked_array <T> x ;
      T temp ;
     
      for ( int k = 0 ; k < n ; k ++ )
            for ( int i = A[k].size - 1 ; i >= 0 ; i -- )
                  for ( int j = 0 ; j < i ; j ++ )
                        if ( A[k].a[j+1] < A[k].a[j] )
                        {
                              temp = A[k].a[j+1] ;
                              A[k].a[j+1] = A[k].a[j] ;
                              A[k].a[j] = temp ;
           
                        } // end if, fors
 
      for ( int i = n - 1 ; i >= 0 ; i -- )
            for ( int j = 0 ; j < i ; j ++ )
                  if ( A[j+1] < A[j] )
                  {
                        x = A[j+1] ;
                        A[j+1] = A[j] ;
                        A[j] = x ;
           
                  } // end if, fors

} //end of sort_obj_array ()

void main()
{
      checked_array <int> * A = ( checked_array <int> * ) new comparable_checked_array <int> [5] ;    
      int a[10], i, j, s ;

      for ( i = 0 ; i < 5 ; i ++ )
      {
            cout << "\n Please enter the elements for array no. " << i + 1 << ": " << endl ;
            
            for ( j = 0 ; j < 10 ; j ++ )
                  cin >> a[j] ; // end nested for
      
            A[i].init ( a, 10 ) ;

      } // end outer for

      sort_obj_array ( A, 5 ) ;

      cout << "\n The sorted array of objects (with individual arrays also sorted) is: " ;

      for ( i = 0 ; i < 5 ; i ++ )
      {
            cout << "\n\n Array No. " << i + 1 << ": " ;
            s = A[i].get_size () ;

            for ( j = 0 ; j < s ; j ++ ) // make use of overloaded operator []
                  cout << A[i][j] ; // end nested for

      } // end outer for
            
} // end of main ()


/* Mayank. */
0
 
LVL 1

Author Comment

by:winner21
ID: 8192942
hi, Mayank, thanks a lot. I compiled the code and get the following error:

error C2248: 'comparable_checked_array<int>::comparable_checked_array<int>' : cannot access private member declared in class 'comparable_checked_array<int>'

However, If I declare the int as public, I got the following error:

no default appropriate constructor.

What shall I do?

Thanks,
0
 
LVL 30

Expert Comment

by:Mayank S
ID: 8193012
OOOOOOOOOOOOOOOoooohhhhhhhh, man! Change the comparable_checked_array class to:

template <class T>
class comparable_checked_array : public checked_array <T>
{
public: // THIS IS THE CHANGE - OTHERWISE THEY'LL ALL BE PRIVATE BY DEFAULT
     comparable_checked_array () : checked_array () // default constructor ()
     {

     } // end of default constuctor ()

     comparable_checked_array ( int s ) : checked_array ( s ) // parameterized constructor ()
     {

     } // end of parameterized constructor ()

     int operator < ( comparable_checked_array & ) ;
     friend void sort_obj_array ( T [], int ) ;

} ; // class definition over


Mayank.

0
 
LVL 1

Author Comment

by:winner21
ID: 8195333
Thanks, Mayank, After I changed, I got the following error:

1) error C2955: 'checked_array' : use of class template requires template argument list

2) error C2614: 'comparable_checked_array<int>' : illegal member initialization: 'checked_array' is not a base or member.

I will try to fix it. However, probably I still need your help.
0
 
LVL 1

Author Comment

by:winner21
ID: 8196188
By the way, in the sort(), since the size is private member of checked_array, the following code

for ( int i = A[k].size - 1 ; i >= 0 ; i -- )

should be changed to:

for ( int i = A[k].get_size()-1 ; i >= 0 ; i -- )

right?

0
 
LVL 1

Author Comment

by:winner21
ID: 8196208
And continued my last notes - the a[] is also a private member of checked_array, do you think this is correct which we used in sort()? Thanks,
0
 
LVL 1

Author Comment

by:winner21
ID: 8196323
I changed the following line in comparable_checked_array class from

 comparable_checked_array():checked_array(){}

to:

 comparable_checked_array():checked_array<T>{}

since the compiler tells me the checked_array argument list is required. However, After I changed this, I got the following error:

error C2059: syntax error : '{', while compiling class-template member function '__thiscall comparable_checked_array<int>::comparable_checked_array<int>(void)'.

By the way, I find in the init(), we used "size" again, but as far as I know, this variable is only private varaible in checked_array, can we use it?
0
 
LVL 1

Author Comment

by:winner21
ID: 8196934
Hi Mayank, just forget the above comments - I think I am very close to the envisioned results. Except one thing -

in the sort(), the following code:

 for(int i=n-1;i>=0;i--)
          for(int j=0;j<i;j++)
               if(A[j+1]<A[j])
               {
                    x=A[j+1];
                    A[j+1]=A[j];
                    A[j]=x;          
               } // end if, fors

always generate errors:

1)error C2676: binary '<' : 'class checked_array<int>' does not define this operator or a conversion to a type acceptable to the predefined operator
2)error C2679: binary '=' : no operator defined which takes a right-hand operand of type 'class checked_array<int>' (or there is no acceptable conversion)

it seems these two errors have the same error source. What could cause this issue?
0
 
LVL 1

Author Comment

by:winner21
ID: 8197085
Continues - From the above errors, I thought there is something wrong with the sort(), currently we pass checked_array A as the first parameter, however when we count the sum of comparable_checked_array for all the elements in A, we failed since the passed parameter A is not comparable_checked_array.

I switched the comparable_checked_array and declare a new function operator< under Checked_array, everything works fine. However what if I need to back to comparable_checked_array? Since this is the one we original need.
0
 
LVL 1

Author Comment

by:winner21
ID: 8197837
Hi, Mayank, I have already completely and successfully finished the code, except - 1) I switched the operator< from comparable_checked_array to checked_array, as this can make the sort() works properly. 2) If I keep the definition you made (I mean the operator<), system will generate the following errors:

1)error C2676: binary '<' : 'class checked_array<int>' does not define this operator or a conversion to a type acceptable to the predefined operator
2)error C2679: binary '=' : no operator defined which takes a right-hand operand of type 'class checked_array<int>' (or there is no acceptable conversion)

By the way, do you mind if I need your email address? Then I can send you the code.

PS. There is a bug in the original code:

comparable_checked_array():checked_array<T>(){} //default constuctor ()

you forget the <T> which is the argument of the checked array.


0
 
LVL 1

Author Comment

by:winner21
ID: 8197849
Excellent helper! Good knowledge! And very patient! Hope we can be friends.
0
 
LVL 1

Author Comment

by:winner21
ID: 8200074
Hi Mayank, Updates and Questions:

Updates:

1. I changed the code T *a; from protected to public in order to make the sort() work. However, I don't think this should be correct.
2. I changed the default constructor in comparable_checked_array to as you missed the <T>

comparable_checked_array():checked_array<T>(){} //default constuctor ()

Questions:

After the above changes, I can only make the first sort() work properly, in other words, the sort() will only sort all elements for the array, it will not sort the entire array as the following error generates:

error C2676: binary '<' : 'class checked_array<int>' does not define this operator or a conversion to a type acceptable to the predefined operator.

I feel we are very close to the routine, can you give me any more idea?

 





0
 
LVL 1

Author Comment

by:winner21
ID: 8200091
Additional Notes for the previous comments:

Since the A[] in sort() is defined as a checked array, however, the operator< is not defined for the checked array, that's why we generate the error when we try to sort the entire array? Mayank, do you think should we change it to comparable checked array, I know this is possible, but how?

0
 
LVL 1

Author Comment

by:winner21
ID: 8200107
By the way, If I have to declare the function template for the sort, can I write the code as following?

Template<Class T, Class ELT>
void sort(T &a, int size);

....
0
 
LVL 1

Author Comment

by:winner21
ID: 8200111
By the way, If I have to declare the function template for the sort, can I write the code as following?

Template<Class T, Class ELT>
void sort(T &a, int size);

....
0
 
LVL 1

Author Comment

by:winner21
ID: 8200145
By the way, If I have to declare the function template for the sort, can I write the code as following?

Template<Class T, Class ELT>
void sort(T &a, int size);

....
0
 
LVL 1

Author Comment

by:winner21
ID: 8200159
By the way, If I have to declare the function template for the sort, can I write the code as following?

Template<Class T, Class ELT>
void sort(T &a, int size);

....
0
 
LVL 1

Author Comment

by:winner21
ID: 8200169
by the way, I feel the sort() doesn't work for regular integer or float type???
0
 
LVL 1

Author Comment

by:winner21
ID: 8200222
by the way, I feel the sort() doesn't work for regular integer or float type???
0
 
LVL 1

Author Comment

by:winner21
ID: 8200267
by the way, I feel the sort() doesn't work for regular integer or float type???
0
 
LVL 1

Author Comment

by:winner21
ID: 8200299
by the way, I feel the sort() doesn't work for regular integer or float type???
0
 
LVL 1

Author Comment

by:winner21
ID: 8200306
by the way, I feel the sort() doesn't work for regular integer or float type???
0
 
LVL 1

Author Comment

by:winner21
ID: 8200338
by the way, I feel the sort() doesn't work for regular integer or float type???
0
 
LVL 30

Expert Comment

by:Mayank S
ID: 8200357
Hi Winner,

Surely we can be friends, pal - removedby_alias99@nospam.com

'a' was not a private member but a protected member. So it is Ok if it is accessed in sort () because it will be accessible by a friend function of a dervied class (comparable_checked_array). I don't see any need to make it public. Again, 'size' is also a protected member, so I really don't see any problem there.

Now, as for sending me the code, I really don't think that I will be able to do anything because I don't have the new version of C++, like I said before. I think what you should do is catch hold of a book and check the syntax of the function definitions and calls - that's it. There are simply some very elementary errors in the syntax, which I don't remmeber very well because its been like 2 years since I worked so much on C++. I'm more into Java now, so I've forgotten the syntax of class templates.

You asked that whether the sort () function will work for integers, floats, etc. I'm a little confused here because I had posted you a different sort_obj_array () function, which was supposed to sort individual objects separately and then sort the array of objects too. So I'm a little confused as to which one you're referring to.

Also, as to your question regarding changing the A[] to comparable_checked_array: you are right, the overloading of < is defined for the comparable_checked_array. Actually, I don't see any problem if you let the array A[] in main () stay as it is, and change simply the checked_array <T> A[] to comparable_checked_array A[]. Again, I don't remember whether a <T> is required here or not - its all a matter of syntax. Please check with some book.

>> Template<Class T, Class ELT>

I don't think that you need 2 types here since in the function, you want to deal with only one type (say, the comparable_checked_array).

Hope that much was of help to you!

Mayank.
0
 
LVL 1

Author Comment

by:winner21
ID: 8200454
Hi,Mayank, Greate hear from you, my eamil address is removedby_alias99@nospam.com

Although I know "a" and "size" are protected variable, Why I always get access-is-not-available problem? Until I changed the T *a from protected to public, it just work.

I will check the rest of tomorrow. It's too late(12 AM)
0
 
LVL 1

Author Comment

by:winner21
ID: 8200469
However, if I changed the checked_array to (comparable_checked_array<T> A[], int n), I got the following error:

 error C2664: 'void __cdecl sort(int [],int)' : cannot convert parameter 1 from 'class checked_array<int> *' to 'int []'
        Types pointed to are unrelated; conversion requires reinterpret_cast, C-style cast or function-style cast
0
 
LVL 1

Author Comment

by:winner21
ID: 8200478
However, if I changed the checked_array to (comparable_checked_array<T> A[], int n), I got the following error:

 error C2664: 'void __cdecl sort(int [],int)' : cannot convert parameter 1 from 'class checked_array<int> *' to 'int []'
        Types pointed to are unrelated; conversion requires reinterpret_cast, C-style cast or function-style cast
0
 
LVL 1

Author Comment

by:winner21
ID: 8200490
However, if I changed the checked_array to (comparable_checked_array<T> A[], int n), I got the following error:

 error C2664: 'void __cdecl sort(int [],int)' : cannot convert parameter 1 from 'class checked_array<int> *' to 'int []'
        Types pointed to are unrelated; conversion requires reinterpret_cast, C-style cast or function-style cast
0
 
LVL 1

Author Comment

by:winner21
ID: 8200507
However, if I changed the checked_array to (comparable_checked_array<T> A[], int n), I got the following error:

 error C2664: 'void __cdecl sort(int [],int)' : cannot convert parameter 1 from 'class checked_array<int> *' to 'int []'
        Types pointed to are unrelated; conversion requires reinterpret_cast, C-style cast or function-style cast
0
 
LVL 1

Author Comment

by:winner21
ID: 8200524
For the Template<class T, class ELT>, I think we need 2 types, one for checked array and another one for comparable checked array, if this is true. How can we call in main()?
0
 
LVL 30

Expert Comment

by:Mayank S
ID: 8200559
>> 'void __cdecl sort(int [],int)'

No.. I told you to use the sort_obj_array () function which I have defined in my code. It is not of the form (int[], int). Please use that function because your sort () function is for ints and not for objects. The sort_obj_array () function is for objects. And change its declaration:

>> friend void sort_obj_array ( T [], int ) ;

to:

friend void sort_obj_array ( comparable_checked_array [], int ) ;

in the class definition of comparable_checked_array.

By mistake, I wrote T[] in the declaration. It should be comparable_checked_array[].

(Again, not sure if the <T> is required or not.... check it both ways if an error is coming or not).

And that is also the reason why it was saying that it cannot access the protected members 'a' and 'size' because the friend declaration was for sort_obj_array ( T[], int ) and not for sort_obj_array ( comparable_checked_array[], int ).

So just change the function declaration as I've told in the class and change the access-scope of 'a' and 'size' back to 'protected'. It'll work. Just check if the <T> is required or not.

>> Template<class T, class ELT>

I still don't understand why it is needed because ultimately, you are referring to just one type of object in the function and that is the comparable_checked_array, and so, you don't need the checked_array there at all.

Hope that helps!

Mayank.
0
 
LVL 1

Author Comment

by:winner21
ID: 8204357
Hi Mayank,

1. Actually I only changed the name from sort_obj_array to sort. Everything else is same.
2. I changed the friend sort(T [], int) to friend sort(comparable_checked_array [], int). However this comes up a new question since when you call the sort(), the first parameter should be the comparable checked array, but as you know the A is a checked array. How is it possible to make this kind of call? That's why I got error.


************Definition of the Comparable_checked_array********************

template <class T>
class comparable_checked_array:public checked_array<T>
{
public:
     comparable_checked_array():checked_array<T>(){} //default constuctor ()
     comparable_checked_array (int s):checked_array(s){} //parameterized constructor ()
     int operator<(comparable_checked_array &);
     friend void sort(comparable_checked_array [],int);//CHANGED March 25, 2003
} ; // class definition over

template<class T>
int comparable_checked_array<T>::operator<(comparable_checked_array & obj)
{
     int mysum=0,othersum=0;

     for(int i=0;i<size;i++)
          mysum+=a[i]; //end for    
     for(int j=0;j<obj.size;j++)
          othersum+=obj.a[j];
     if (mysum < othersum )
          return 1;
     return 0;  
} //end of operator<()
*********************************************************


Therefore, I think we should change the sort() to:

Template<class T>
void sort(comparable_checked_array<T> A[], int n)
{
     comparable_checked_array<T> x;
     T temp;
   
     for(int k=0;k<n;k++)
          for(int i=A[k].get_size()-1;i>=0;i--)
               for(int j=0;j<i;j++)
                    if(A[k].a[j+1]<A[k].a[j])
                    {
                       temp=A[k].a[j+1];
                       A[k].a[j+1]=A[k].a[j];
                       A[k].a[j]=temp;          
                    }  

     for(int i=n-1;i>=0;i--)
          for(int j=0;j<i;j++)
               if(A[j+1]<A[j])  
               {
                      x=A[j+1];
                  A[j+1]=A[j];
                  A[j]=x;          
               }
} //end of sort()

However, when we call the sort() in main() as following:

sort(A,3); where A is the checked_array.

I don't think this will work.

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

Or I changed the sort() as following:

Template<class T>
void sort(checked_array<T> A[], int n)
{
     comparable_checked_array<T> x;
     T temp;
   
     for(int k=0;k<n;k++)
          for(int i=A[k].get_size()-1;i>=0;i--)
               for(int j=0;j<i;j++)
                    if(A[k].a[j+1]<A[k].a[j])
                    {
                       temp=A[k].a[j+1];
                       A[k].a[j+1]=A[k].a[j];
                       A[k].a[j]=temp;          
                    }  

     for(int i=n-1;i>=0;i--)
          for(int j=0;j<i;j++)
               if(A[j+1]<A[j])  
               {
                      x=A[j+1];
                  A[j+1]=A[j];
                  A[j]=x;          
               }
} //end of sort()

which will NOT follow up the "friend sort(comparable_checked_array)" in the definition of the comparable_checked_array, however it will allow we pass the checked array A in main() when we call sort().

Meanwhile, if we declare:

friend void sort(comparable_checked_array<T> [], int). Neither the above case 1 nor case 2 will work, since either of them breakes the regulation. And In case 2, I will get the "a" and "size" not-accessiable error.

I hope you can understand what I said.

Just in case, I will attach my code in the following comments, hope you can take a final look.

Thanks,


0
 
LVL 1

Author Comment

by:winner21
ID: 8204390
*********Entire Code*************************
#include <iostream.h>
#include <stdio.h>
#include <stdlib.h>

template <class T>
class checked_array
{
protected:
     int size;
     T *a;
public:             
       checked_array(){
       size=0;
       a=NULL;
     }//end of default constructor ()

     checked_array (int s){
       size=s;
       a=new T[size];
     } // end of parameterized constructor ()

     void init(T [],int);
     T & operator[](int);    
     int get_size(){return size;}
       //int operator<(checked_array &);
}; // class definition over

class OutOfRange{};

template <class T>
T &checked_array<T>::operator[](int i)
{
     if ((i>=0) && (i<size))
          return a[i];
     clog << "Checked-array::operator[] index out of bounds." << endl;
     throw OutOfRange();
} // end of operator[]

template<class T>
void checked_array<T>::init(T b[],int n)
{
     size=n;
     a=new T[size];
     for(int i=0;i<size;i++)
        a[i]=b[i];  
} // end of init()

template <class T>
class comparable_checked_array:public checked_array<T>
{
public:
     comparable_checked_array():checked_array<T>(){} //default constuctor ()
     comparable_checked_array (int s):checked_array(s){} //parameterized constructor ()
     int operator<(comparable_checked_array &);
     friend void sort(comparable_checked_array [],int);//CHANGED March 25, 2003
} ; // class definition over

template<class T>
int comparable_checked_array<T>::operator<(comparable_checked_array & obj)
{
     int mysum=0,othersum=0;

     for(int i=0;i<size;i++)
          mysum+=a[i]; //end for    
     for(int j=0;j<obj.size;j++)
          othersum+=obj.a[j];
     if (mysum < othersum )
          return 1;
     return 0;  
} //end of operator<()

template<class T>
void sort(checked_array<T> A[],int n)//make it a friend of the comparable_checked_array
{
     comparable_checked_array<T> x;
     T temp;
   
     for(int k=0;k<n;k++)
          for(int i=A[k].get_size()-1;i>=0;i--)
               for(int j=0;j<i;j++)
                    if(A[k].a[j+1]<A[k].a[j])
                    {
                       temp=A[k].a[j+1];
                       A[k].a[j+1]=A[k].a[j];
                       A[k].a[j]=temp;          
                    }  

     for(int i=n-1;i>=0;i--)
          for(int j=0;j<i;j++)
               if(A[j+1]<A[j])  
               {
                          x=A[j+1];
                  A[j+1]=A[j];
                  A[j]=x;          
               }
} //end of sort()

void main()
{
       int ingelements;
       cout << "Enter the number of elements you want to create for checked array A: ";
       cin >> ingelements;
     checked_array<int> * A=(checked_array<int> *) new comparable_checked_array<int> [ingelements];    
      
     int a[3],i,j,s;
     for(i=0;i<ingelements;i++)
     {
          cout << "\nPlease enter the elements for Array No. " << i+1 << ": " << endl;          
          for(j=0;j<3;j++)
               cin >> a[j];    
          A[i].init(a,3);
     } // end outer for

     sort(A,ingelements);
     cout << "\nThe sorted array of objects (with individual arrays also sorted) is:";
     for (i=0;i<ingelements;i++)
     {
          cout << "\n\n Array No. " << i+1 << ": ";
          s=A[i].get_size();
          for (j=0;j<s;j++)
               cout << A[i][j] << " "; //end nested for
     }          
} //end of main()

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


1) You can see from the code, I changed back for a and size to protected. However I got the not-accessible error. I don't know if this is related to the definition of comparable_checked _array.
2) If you look at the sort(), we passed A which is the checked array, however the first parameter is comparable_checked_array, I think this is wrong?
3) A[i].a[j] should be the comparable_checked_array if A is the checked array, am I correct on this?

Thanks,
0
 
LVL 30

Expert Comment

by:Mayank S
ID: 8207796
>> I changed back for a and size to protected. However I got the not-accessible error.

Because inside the class, the friend function declaration is:

>> friend void sort ( comparable_checked_array [], int ) ;

And outside, the function definition says:

>> template <class T>
>> void sort ( checked_array <T> A[], int n )
>> {
>>     comparable_checked_array <T> x ;
>>     T temp ;


Got it?? The data type of the first argument is different in both cases. So, the defined function does not match the function which was declared as a friend. Make them consistent. Make it:

friend void sort ( checked_array [], int ) ;

in the class definition.

Then, you can also access 'size' directly instead of using get_size () in the function.

>> we passed A which is the checked array, however the first parameter is comparable_checked_array

Base class arguments can receive derived class arguments, just like base class pointers can point to derived class pointers. If you're getting an error on accessing the overloaded < operator in the sort () function, then you can remove the operator < () function from the comparable_checked_array class to the checked_array class and convert its argument to checked_array type.

>> A[i].a[j] should be the comparable_checked_array if A is the checked array

Since the operator [] is overloaded for the checked_array, the derived class objects can also use it. And since [] is overloaded for an object of checked_array (say, X), we can write X[i] to get the value of the element in the i'th index in data-member 'a' of X. Sameway, since each A[i] is an object, we can write A[i][j] to get the value of the j'th element.


Mayank.
0
 
LVL 1

Author Comment

by:winner21
ID: 8211971
I have already finished it. Everything works as expected. Thanks. I will contact you by email next time.
0
 
LVL 30

Expert Comment

by:Mayank S
ID: 8215380
I hope that you still went through my last post.

Mayank.
0

Featured Post

[Webinar] How Hackers Steal Your Credentials

Do You Know How Hackers Steal Your Credentials? Join us and Skyport Systems to learn how hackers steal your credentials and why Active Directory must be secure to stop them.

Question has a verified solution.

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

Unlike C#, C++ doesn't have native support for sealing classes (so they cannot be sub-classed). At the cost of a virtual base class pointer it is possible to implement a pseudo sealing mechanism The trick is to virtually inherit from a base class…
Templates For Beginners Or How To Encourage The Compiler To Work For You Introduction This tutorial is targeted at the reader who is, perhaps, familiar with the basics of C++ but would prefer a little slower introduction to the more ad…
The goal of the video will be to teach the user the difference and consequence of passing data by value vs passing data by reference in C++. An example of passing data by value as well as an example of passing data by reference will be be given. Bot…
The viewer will learn additional member functions of the vector class. Specifically, the capacity and swap member functions will be introduced.
Suggested Courses

762 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