c++ - 在函数 C++ 中使用二维质量

标签 c++ function

当我编译这段代码(如下)时,它给了我一个错误:

prog.cpp: In function 'int main()':
prog.cpp:46:37: error: cannot convert 'int (*)[n]' to 'int**' for argument '4' to 'void dfs(int, std::vector<int>&, int, int**)'
     dfs(1, used, n, Adjacency_matrix);

据我了解,这是因为错误地调用了二维 massive 函数。我需要在此代码中更正什么,以便函数接受我的大量。

附注对不起我的英语:)

#include <iostream>
#include <algorithm>
#include <cmath>
#include <vector>

void dfs(int i, std::vector <int> &used, int n, int (&Adjacency_matrix)[n][n]) {
    used[i] = 1;
    for (int j = 0; j < n; ++j) {
        if ((Adjacency_matrix[i][j] == 1) && (used[j] == 0))
            dfs(j, used, n, Adjacency_matrix);
    }
}

double distance(int x1, int y1, int x2, int y2) {
    return sqrt((x1 - x2)*(x1 - x2) + (y1 - y2)*(y1 - y2));
}

int main() {
    int n, k;
    std::cin >> n >> k;

    int coordinates[n][2];

    for (int i = 0; i < n; ++i) {
        std::cin >> coordinates[i][1];
        std::cin >> coordinates[i][2];
    }

    int Adjacency_matrix[n][n];

    for (int i = 0; i < n; ++i) {
        for (int j = 0; j < n; ++j) {
            if (i == j)
                Adjacency_matrix[i][i] = 0;
            if ((i != j) && (distance(coordinates[i][1], coordinates[i][2], coordinates[j][1], coordinates[j][2]) <= k))
                Adjacency_matrix[i][j] = 1;
            if ((i != j) && (distance(coordinates[i][1], coordinates[i][2], coordinates[j][1], coordinates[j][2]) > k))
                Adjacency_matrix[i][j] = 0;
        }
    }

    std::vector <int> used;
    for (int i = 0; i < n; ++i)
        used.push_back(0);

    dfs(1, used, n, Adjacency_matrix);
    for (int i = 0; i < n; ++i) {
        if (used[i] == 0)
            std::cout << "NO";
            exit(0);
    }
    std::cout << "YES";
}

最佳答案

您的 dsf 函数声明是错误的。使用

template<size_t N>
void dfs(int i, std::vector <int> &used, int (&Adjacency_matrix)[N][N]) 
{ ... }

捕获通过引用传递的数组的大小。 接下来,您不能在标准 C++ 中使用可变大小的数组,

int Adjacency_matrix[n][n]; 

无效,除非 nconstconstexpr。因此,您不能从 cin 读取它。如果您想要动态大小,请使用 std::vector 或指针。

关于c++ - 在函数 C++ 中使用二维质量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28920671/

相关文章:

c++ - CMake 命令行定义不会延续到工具链文件

c++ - DirectX中是否有指定的Ray对象

C++:将参数应用于函数范围

c++ - C/C++的rand()怎么能这么快生成随机数呢?

c++ - 在某些情况下使用 auto 作为返回类型和返回值 nullptr

function - 类型和功能

javascript - 如何使用 00 :00 time format?(秒:毫秒)修复我的 Javascript 秒表

c - 如何使函数 printf 将其输出输出到文件或控制台上?

javascript - 对象内对象的原型(prototype)

c++ - 使用 iostream 消失的段错误