Is the book wrong?

template <typename T>
  class Table {
    public:
      Table();
      Table(int m, int n);
      Table(int m, int n, const T& value);
      Table(const Table<T>& rhs);
      ~Table();
      Table<T>& operator=(const Table& rhs);
      T& operator()(int i, int j);
      int numRows()const;
      int numCols()const;
      void resize(int m, int n);
      void resize(int m, int n, const T& value);
    private:
      // Make private because this method should only be used
      // internally by the class.
      void destroy();
    private:
      int mNumRows;
      int mNumCols;
      T** mDataMatrix;
  };

template <typename T>
  void Table<T>::destroy() {
    // Does the matrix exist?
    if (mDataMatrix) {
      for (int i = 0; i < _m; ++i) {
        // Does the ith row exist?
        if (mDataMatrix[i]) {
          // Yes, delete it.
          delete[]mDataMatrix[i];
          mDataMatrix[i] = 0;
        }
      }

      // Delete the row-array.
      delete[] mDataMatrix;
      mDataMatrix = 0;
    }

    mNumRows = 0;
    mNumCols = 0;
  }

This is a sample code that I got from a book. It demonstrates how to destroy or free a 2x2 matrix, where mDataMatrix is ​​a pointer to an array of pointers.

I do not understand this part:

for(int i = 0; i < _m; ++i) {
  // Does the ith row exist?
  if (mDataMatrix[i]) {
    //.….

  }
}

I do not know why the book uses _m for the maximum number of row-ptr. There was not even a variable in the class; the variable for max row is mNumRows. Maybe this is a specific compiler variable? Another thing is that I'm rather confused, why is it ++ i? pre-operator, why not i ++? Will it be different if I change it to i ++?

+3
source share
6 answers

One more thing, I'm rather confused, why is it ++ i? pre-operator, why not i ++? Will it be different if I change it to i ++?

++i : increment i, i. i++ i - ( temp), increment i, temp.

, i++ , ++i.

, ++i , - . (, -, .) ++i i++ , , ( incremented variable vs. old value), ( ).

+5

, , , , .

, ++ vs. ++, (++ i) , , postfix . .-

int i=1;
std::cout << i++ << std::endl;  // output:  1
std::cout << i << std::endl     // output:  2
std::cout << ++i << std::endl   // output:  3

postfix-no, . , , ++ .

+3

_m , . , , new - (, , , addRow). mNumRows, .

++i i++ , . , ( ) .

+2

, -.

. , , , ++ over ++ i, , , .

0

, . , for, , , (.. i < _m), , .

0

- , 2x2. , 4 3 , , , , .

:

T* mData = new T[2*2];

:

T& operator()(size_t r, size_t c) { return mData[r * mNbRows + c]; }

( , major), destroy :

template <class T>
void Table<T>::destroy()
{
  delete[] mData;
  mData = 0;
  mNbRows = 0;
  mNbColumns = 0;
}

, if: , delete , .

, , int , - Table? , (, size_t) .

0

Source: https://habr.com/ru/post/1754594/


All Articles