在 C++ 中初始化邻接矩阵

Initializing an adjacency matrix in c++

我正在研究 C++ 中的图形实现,并遇到了一个对我来说最有意义的邻接矩阵的实现。该实现使用 "init" 函数来初始化矩阵:

void init(int n) {

    numVertex = 0;
    numEdge = 0;

    mark = new int[n]; //initialize mark array
    for (int i = 0; i < numVertex; i++) {
        mark[i] = 0;
    }

    matrix = (int**) new int*[numVertex]; //make matrix
    for (int i = 0; i < numVertex; i++) {
        matrix[i] = new int[numVertex];
    }

    for (int i = 0; i < numVertex; i++) { //mark all matrix cells as false
        for (int j = 0; j < numVertex; j++) {
            matrix[i][j] = 0;
        }
    }
}

我感到困惑的是:

 matrix = (int**) new int*[numVertex]; //make matrix

(int**) 方面有什么作用?为什么我会选择使用它而不是 matrix = new int**[numVertex];

非常感谢!

(int**)value 是 C 风格的转换操作。

备注:

  • 不要在 C++ 中使用它们,它往往会导致或隐藏问题,例如赋值的右侧和左侧之间的不匹配。
  • 代码质量比较低,妥妥的C++宁愿用std::vector
  • 代码也不完整,因此无法确定其功能。

请注意,您提到的 matrix = new int**[numVertex]; 将创建(对于此示例)一个 3D 数组,因为您将拥有 int**.

numVertex 个条目

(int**) 转换没有完成多少,如果有的话,因为如果 matrix 是类型 int**,则不需要转换(你得到一个int** 已经来自 new).

如果列维度是固定的,你可以在那里使用数组向量。
godbolt
wandbox

#include <vector>
#include <array>
#include <iostream>
#include <iomanip>

template<typename T, int col>
using row_templ = std::array<T,col>;

template<typename T, int col, template <typename,int> typename U = row_templ>
using mat_templ = std::vector<U<T,col>>;

int main()
{
    constexpr int numVertex = 30;
    constexpr int numEdge = 30;
    constexpr int numCol = numVertex;
    int numRow = numEdge;
    using row_t = row_templ<int, numCol>; // alias to the explicit class template specialization
    using mat_t = mat_templ<int, numCol>;
    auto make_mat = [&](){ return mat_t(numRow); }; // define a maker if lazy

    mat_t my_mat(numRow);
    mat_t my_mat2 = make_mat(); // or just use our maker
    // Due to that default allocator uses value initialization, a.k.a T().
    // At this point, all positions are value init to int(), which is zero,
    // from value init of array<int, col>() by the default allocator.
    // numVertex x numEdge is one solid contaguous chunk and now ready to roll.

    // range for
    for (row_t r : my_mat) {
        for (int n : r) {
            std::cout << std::setw(4) << n;
        }
        std::cout << '\n';
    }

    // classic for
    for (int i = 0; i < numRow; ++i) {
        for (int j = 0; j < numCol; ++j) {
            std::cout << std::setw(4) << (my_mat2[i][j] = i*numRow + numCol);
        }
        std::cout << '\n';
    }

}