“无匹配函数”和“无法初始化char(*)[*]

时间:2018-10-05 10:08:58

标签: c++ c++11

我是C ++新手,我刚刚开始学习它,我的任务之一是打印N-Queens问题的解决方案,根据用户的输入,板子将为N * N。我的IDE不断向我显示代码中无法理解的错误,尽管对我来说看起来不错。

#include <iostream>
#include <array>
#include <stdexcept>

using namespace std;

int N;

bool safe(char board[N][N], int row, int col)
{
  //checks if it's safe to place a queen
  //doesn't give me any errors
}

bool placeQueen(char board[N][N], int col)
{

    for (int i = 0; i < N; i++)
    {

        if ( safe(board, i, col) )
        // says there is no matching function to call safe

        {

        board[i][col] = 1;

        if ( placeQueen(board, col + 1) ){
        //says cannot initialize parameter of type char(*)[*]
        //with an Ivalue of type char(*)[N]
            return true;
        }

        board[i][col] = 0;
        }
    }
    return false;
}
void printAnswer(char board[N][N]){
//prints the final answer
}

int main()
{
int i, j;
try{
    cout << "Enter the number of queens: ";
    cin >> N;

    char board[N][N];
    for (int i = 0; i < N; i++){
        for (int j = 0; i < N; i++){
            board[i][j] = '.';
        }
    }

    if ( placeQueen(board, 0) == false )
    //no matching function to call placeQueen
    {
        throw runtime_error("Solution does not exist.");
        return 0;
    }

    printAnswer(board);
    //no matching function to call printAnswer
}
catch (runtime_error& excpt){
    cout << excpt.what();
}

return 0;
}

可能只是我很愚蠢,但是可以得到帮助,谢谢!

1 个答案:

答案 0 :(得分:0)

当N不是编译时间常数时,

char board[N][N]不是C ++。这是gcc的扩展,实际上默认情况下不应启用。

您不是要定义采用(C样式)char数组的函数,而是要采用标准C ++和behaves differently to how it would in C.

中未定义的函数。

您应该改为将其他类型定义为您的木板,例如using Board = std::vector<std::vector<char>>;。然后,您可以传递(引用)此类型。

#include <iostream>
#include <vector>

using Board = std::vector<std::vector<char>>;

bool safe(const Board & board, int row, int col)
{
  //checks if it's safe to place a queen
  //doesn't give me any errors
}

bool placeQueen(Board & board, int col)
{    
    for (int i = 0; i < N; i++)
    {    
        if (safe(board, i, col) )
        {
            board[i][col] = 1;

            if ( placeQueen(board, col + 1) ){
                return true;
            }

            board[i][col] = 0;
        }
    }
    return false;
}

void printAnswer(const Board & board){
//prints the final answer
}

int main()
{
    std::cout << "Enter the number of queens: ";
    int N;
    std::cin >> N;

    Board board{N, {N, '.'}}; // Initialise N vectors of N '.'

    if (!placeQueen(board, 0))
    {
        std::cout << "Solution does not exist.";
        return 0;
    }

    printAnswer(board);

    return 0;
}