繁体   English   中英

在 CPP class 的构造函数中初始化二维数组

[英]Initialize 2D array in constructor of CPP class

我想知道在 cpp class 中初始化二维数组的最佳方法是什么。 在调用构造函数之前我不知道它的大小,即

Header 文件包含:

private:
    int size;
    bool* visited;
    int edges;
    int** matrix;

默认构造函数(现在):

Digraph::Digraph(int n) {
  int rows = (n * (n-1)/2);
  int columns = 2;

  matrix = new int[rows][2];

  visited[size] = { 0 };

  size = n;
  edges = 0;
}

我想要的是一个 N 行 2 列的二维数组。

这当前返回error: cannot convert 'int (*)[2]' to 'int**' in assignment

注意:我不能使用 Vectors,所以请不要推荐它们。

matrix = new int[rows][2]; 无效。 试试这个:

private:
    int size;
    bool* visited;
    int edges;
    int** matrix;
    int rows;
    int columns;

...

Digraph::Digraph(int n) {
  size = n;
  edges = 0;

  rows = (n * (n-1)/2);
  columns = 2;

  matrix = new int*[rows];
  for(int x = 0; x < rows; ++x)
    matrix[x] = new int[columns];

  visited = new bool[size];
  for(int x = 0; x < size; ++x)
    visited[x] = false;
}

Digraph::~Digraph() {
  for(int x = 0; x < rows; ++x) {
    delete[] matrix[x];
  }
  delete[] matrix;

  delete[] visited;
}

您还需要根据 3/5/0 的规则实现(或禁用)复制构造函数和复制赋值运算符,最好是移动构造函数和移动赋值运算符,例如:

Digraph::Digraph(const Digraph &src) {
  size = src.size;
  edges = src.edges;

  rows = src.rows;
  columns = src.columns;

  matrix = new int*[rows];
  for(int x = 0; x < rows; ++x) {
    matrix[x] = new int[columns];
    for (int y = 0; y < columns; ++y)
      matrix[x][y] = src.matrix[x][y];
  }

  visited = new bool[size];
  for(int x = 0; x < size; ++x)
    visited[x] = src.visited[x];
}

Digraph::Digraph(Digraph &&src) {
  size = 0;
  edges = 0;
  rows = 0;
  columns = 0;
  matrix = nullptr;
  visited = nullptr;

  src.swap(*this);
}

void Digraph::swap(Digraph &other) {
  std::swap(size, other.size);
  std::swap(edges, other.edges);
  std::swap(rows, other.rows);
  std::swap(columns, other.columns);
  std::swap(matrix, src.matrix);
  std::swap(visited, src.visited);
}

Digraph& Digraph::operator=(Digraph rhs) {
    Digraph temp(std::move(rhs));
    temp.swap(*this);
    return this;
}

更好的设计是使用std::vector而不是new[] ,并让它为您处理所有 memory 管理和复制/移动,例如:

#include <vector>

private:
    int size;
    std::vector<bool> visited;
    int edges;
    std::vector<std::vector<int>> matrix;

...

Digraph::Digraph(int n) {
  size = n;
  edges = 0;

  int rows = (n * (n-1)/2);
  int columns = 2;

  matrix.resize(rows);
  for(int x = 0; x < rows; ++x)
      matrix[x].resize(columns);

  visited.resize(size);
}

// implicitly-generated copy/move constructors, copy/move assignment operators,
// and destructor will suffice, so no need to implement them manually...

如果您不能使用std::vector ,请考虑实现您自己的vector class 并实现适当的语义,然后改用它。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM