Creating matrix using map container

2019-09-03 08:29发布

问题:

   template < class A, class B, class C> class Matrix
  { 
    public:

   typedef map<B,C> M2; // for putting 1D info  
   typedef map<A,M2> M1;
   map<M1, M2 > data; 
   M1 m1;
   M2 m2;
   typedef  typename map<B,C>::iterator iterator2;
   iterator2 itr2; 
   typedef  typename map<A,M2>::iterator iterator1;
   iterator1 itr1;   
    Matrix()                             // default constructor
    { 
      m2.insert(pair<int,double> (1,10));
      m2.insert(pair<int,double> (2,20));
      m2.insert(pair<int,double> (3,30));
        m1.insert(pair <int, M2> (1,m2));
        m2.clear();

     m2.insert(pair<int,double> (1,40));
     m2.insert(pair<int,double> (2,50));
     m2.insert(pair<int,double> (3,60));
        m1.insert(pair <int, M2> (2,m2));
        m2.clear();

     m2.insert(pair<int,double> (1,70));
     m2.insert(pair<int,double> (2,80));
     m2.insert(pair<int,double> (3,90));
        m1.insert(pair <int, M2> (3,m2));
        m2.clear();                    }



    Matrix(const map<M1, M2>& ar)              //copy constructor 
    { m1 = ar.m1; }


    Matrix<A, B, C >& operator = (const Matrix<A, B, C >& ass)    //assignment
    { if (this==&ass) return *this;
      m1 = ass.m1; return *this; }


    const C& operator () ( int& index1,  int& index2 )  //for accessing/modifying data
     {    itr1 = m1.begin();
          advance(itr1,  index1 - 1);
          m2 = (*itr1).second;  
          itr2 = m2.begin();
          advance(itr2,  index2 - 1);             
          return (*itr2).second;      }
 };


int main()
{ 
  Matrix <int,int,double> mtr; 

   cout<< mtr(2,2);

    return 0;
  }

If I compile the above program I'm getting the following error "cannot convert 'Matrix<int, int, double>' to 'double' in assignment." I think there is a problem in the way I have tried to overload the operators but have been unable to solve it so far...

I know this isn't an efficient way of creating Matrices but since I'm a beginner ,it would help if you can help me understand the problem behind this code...

Problem Solved! Thanks

回答1:

This one may not resolve all your problems but it's an outstanding issue:

Matrix <int,int,double> mtr(); 

This line of code doesn't do what you thought. It doesn't define object mtr, instead it declares function which returns Matrix <int,int,double> type.

To define object mtr

Matrix <int,int,double> mtr;

Also, map iterator is not random_access_iterator, you can't do

itr2 = m2.begin()+index2-1;

Try:

itr2 = std::advance(m2.begin(),  index2 - 1);