首页 > 解决方案 > 填字游戏出现错误:'operator==' 不匹配

问题描述

首先,如果这是重新发布,我想对这个问题表示抱歉。我是 c++ stl 的新手,在这一点上被卡住了。我已经创建了这个函数来解决 c++ 中的填字游戏,但它向我展示了

prog.cpp:17:49: 错误: 'operator==' 不匹配(操作数类型为 '__gnu_cxx::__alloc_traitsstd::allocator<std::__cxx11::basic_string<char > >::value_type {aka std:: __cxx11::basic_string}' 和 '__gnu_cxx::__alloc_traitsstd::allocator<char >::value_type {aka char}')

if(matrix[i][j]=='-' || 矩阵[i][j]==word[0])

void solve(vector<vector<string>> &matrix,vector<string> &puzzleWords,int idx)
{
    if(idx==puzzleWords.size())
    {
        return;
    }
    string word=puzzleWords[idx];
    for(int i=0;i<matrix.size();i++)
    {
        for(int j=0;j<matrix[i].size();j++)
        {
            if(matrix[i][j]=='-' || matrix[i][j]==word[0])
            {
                if(canPlacedHorizontally(matrix,word,i,j))
                {
                    vector<bool> wePlaced=placeWordHorizontally(matrix,word,i,j);
                    solution(matrix,word,idx+1);
                    unplaceWordHorizontally(matrix,wePlaced,i,j);
                }
                
                if(canPlacedVertically(matrix,word,i,j))
                {
                    vector<bool> wePlaced=placeWordVertically(matrix,word,i,j);
                    solution(matrix,word,idx+1);
                    unplaceWordVertically(matrix,wePlaced,i,j);
                }
            }
        }
    }
}

标签: c++

解决方案


您显然对字符串(字符序列)和字符(单个字符)感到困惑。

看看这段代码

if(matrix[i][j]=='-' || matrix[i][j]==word[0])

matrix[i][j]是字符串(因为matrix是字符串的 2D 向量)但是'-'是 char 并且word[0]是 char(因为word是字符串)。您不能比较字符串和字符是否相等。

您的填字游戏有一个 2D 向量,但该填字游戏的每个方块都是一个字符串。大多数填字游戏你只能在每个方格写一个字母,所以可能你应该有这个

void solve(vector<vector<char>> &matrix,vector<string> &puzzleWords,int idx)

通过该更改,上面的 if 语句将编译,因为您将比较字符与字符,而不是字符与字符串。


推荐阅读