Search code examples
c++arraysunsignedclass-template

Class template for 2 dimension array that might be used with sever data types in main()


I have to create a class template for 2 dimension array; every variable in the array would get a random value [65;90], I need to find the MAX value in the array. But in class template data type should be unspecified, so later I could use it with any - int/char etc in main().

I have tried several ways to initialize the array, however it still doesnt work. Now here is one part to put the values in the array and 2nd to print().

#include <iostream> 
#include <cstdlib>
using namespace std; 
  
template <typename T> 
class Array { 
private: 
    T **ptr; 
public: 
    Array(T arr[7][12]); 
    void print(); 
}; 
  
template <typename T> 
Array<T>::Array(T arr[7][12]) { 
    ptr = new T[7][12]; 
    for(int i = 0; i < 7; i++) {
        for (int j=0;j<12;j++) {
            arr[i][j]=rand()%26+65;
            ptr[i][j]=arr[i][j];
        }
    }
} 
  
template <typename T> 
void Array<T>::print() { 
    for(int i = 0; i < 7; i++) {
        for (int j=0; j<12; j++) {
            cout<<*(ptr+j)<<" ";
        }
        cout<<"\n";
    }
    cout<<endl; 
} 
  
int main() { 
    int arr[7][12];
    Array<int> a(arr[7][12]); 
    a.print(); 
    return 0; 
} 

Solution

  • I think that this is what you want

    #include <iostream> 
    #include <cstdlib>
    using namespace std; 
      
    template <typename T> 
    class Array { 
    private: 
        T **ptr; 
    public: 
        Array(T arr[][12]); 
        void print(); 
    }; 
      
    template <typename T> 
    Array<T>::Array(T arr[][12]) { 
        ptr = new T *[7];
        for(int i = 0; i < 7; i++) {
            ptr[i] = new T[12];
            for (int j=0;j<12;j++) {
                arr[i][j]=rand()%26+65;
                ptr[i][j]=arr[i][j];
            }
        }
    } 
      
    template <typename T> 
    void Array<T>::print() { 
        for(int i = 0; i < 7; i++) {
            for (int j=0; j<12; j++) {
                cout<<ptr[i][j]<<" ";
            }
            cout<<"\n";
        }
        cout<<endl; 
    } 
      
    int main() { 
        int arr[7][12];
        Array<int> a(arr); 
        a.print(); 
        return 0; 
    } 
    

    Here is ways that you can pass 2D array Passing a 2D array to a C++ function