home *** CD-ROM | disk | FTP | other *** search
/ NetNews Usenet Archive 1992 #26 / NN_1992_26.iso / spool / comp / lang / cplus / 15976 < prev    next >
Encoding:
Text File  |  1992-11-09  |  2.0 KB  |  74 lines

  1. Path: sparky!uunet!spool.mu.edu!agate!doc.ic.ac.uk!uknet!mcsun!sunic!seunet!sysinno!usoderberg
  2. From: usoderberg@sysinno.se (Ulf Soderberg)
  3. Newsgroups: comp.lang.c++
  4. Subject: operator [][]
  5. Message-ID: <721334957snx@sysinno.se>
  6. Date: 9 Nov 92 18:49:17 GMT
  7. References: <BxFt8r.2Kt@cs.columbia.edu>
  8. Reply-To: usoderberg@sysinno.se
  9. Organization: System Innovation AB
  10. Lines: 62
  11.  
  12.  
  13. In article <BxFt8r.2Kt@cs.columbia.edu> duanyang@cs.columbia.edu writes:
  14.  
  15.  > 
  16.  > for multiple dimension array, is it possible to define 
  17.  > an operator [][](say for two dimensions)? I try to define 
  18.  > it as 
  19.  > int & operator[][] (int, int);
  20.  > 
  21.  > which g++ complains about it. 
  22.  > 
  23.  > any idea or just sth is wrong with my try? 
  24.  > 
  25.  > 
  26.  > -- 
  27.  > Duanyang Guo             |     (212)939-7098(O),   663-8904(H)   
  28.  > CS Dept, Columbia Univ.  |      Rm 625, CEPSR
  29.  > New York,     NY 10027   |      Email:duanyang@cs.columbia.edu  
  30.  > 
  31.  > 
  32.  
  33. First define a vector of int's, then define a vector of vectors of int's.
  34.  
  35. Ex.
  36. class Ivect {
  37.     int *vec;
  38.  
  39. public:
  40.     Ivec(int n)               { vec = new int[n]; }
  41.     int &operator[](int idx)  { return vec[idx]; }
  42. };
  43.  
  44. class Imat {
  45.     Ivec **mat;
  46.  
  47. public:
  48.     Imat(int m, int n)
  49.     {
  50.         mat = new (Ivec *)[m];
  51.         for (int i = 0; i < m; i++)
  52.             mat[i] = new Ivec(n);
  53.     }
  54.  
  55.     Ivec &operator[](int idx)  { return *mat[idx]; }
  56. };
  57.  
  58. Then I think it is possible to do like this:
  59.  
  60.     Imat m(4, 3);
  61.  
  62.     for (int i = 0; i < 4; i++)
  63.         for (int j = 0; j < 3; j++)
  64.             m[i][j] = 0;
  65.  
  66. -----------------------------------------------------------------------------
  67. Ulf Soderberg                                 Telephone: +46 8 6300630
  68. usoderberg@sysinno.se                               Fax: +46 8 6300639
  69.                                                 Address: System Innovation AB
  70.                                                          Polygonvagen 53-55
  71.                                                          PO.Box 7105
  72.                                                          S183 07 Taby
  73.                                                          SWEDEN
  74.