[英]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.