A proper way to create a matrix in c++

后端 未结 10 2371
無奈伤痛
無奈伤痛 2020-11-27 05:33

I want to create an adjacency matrix for a graph. Since I read it is not safe to use arrays of the form matrix[x][y] because they don\'t check for range, I deci

10条回答
  •  生来不讨喜
    2020-11-27 06:18

    Best way:

    Make your own matrix class, that way you control every last aspect of it, including range checking.

    eg. If you like the "[x][y]" notation, do this:

    class my_matrix {
      std::vector >m;
    public:
      my_matrix(unsigned int x, unsigned int y) {
        m.resize(x, std::vector(y,false));
      }
      class matrix_row {
        std::vector& row;
      public:
        matrix_row(std::vector& r) : row(r) {
        }
        bool& operator[](unsigned int y) {
          return row.at(y);
        }
      };
      matrix_row& operator[](unsigned int x) {
        return matrix_row(m.at(x));
      }
    };
    // Example usage
    my_matrix mm(100,100);
    mm[10][10] = true;
    

    nb. If you program like this then C++ is just as safe as all those other "safe" languages.

提交回复
热议问题