首页 > 解决方案 > 这两个操作在 C++ 中不是一回事吗?

问题描述

我已经声明了一个二维数组类型bool,我想用false. 我对此代码(如下所示)有此要求,这是关于“通配符字符串匹配”的问题

我尝试了 2 种方法来初始化布尔矩阵false。第一种方法是bool lookup[n + 1][m + 1]={false};,第二种方法是memset(lookup, false, sizeof(lookup));

当我测试我的代码时,第一种方法是给我一个错误的答案。为什么会这样?我已附上我的代码。

// C++ program to implement wildcard
// pattern matching algorithm
#include <bits/stdc++.h>
using namespace std;

// Function that matches input str with
// given wildcard pattern
bool strmatch(char str[], char pattern[], int n, int m)
{
    

    // lookup table for storing results of
    // subproblems
    bool lookup[n + 1][m + 1];

    // initailze lookup table to false
    memset(lookup, false, sizeof(lookup));

    // empty pattern can match with empty string
    lookup[0][0] = true;

    // Only '*' can match with empty string
    for (int j = 1; j <= m; j++)
        if (pattern[j - 1] == '*')
            lookup[0][j] = lookup[0][j - 1];

    // fill the table in bottom-up fashion
    for (int i = 1; i <= n; i++) {
        for (int j = 1; j <= m; j++) {
            
            if (pattern[j - 1] == '*')
                lookup[i][j]
                    = lookup[i][j - 1] || lookup[i - 1][j];

            else if (pattern[j - 1] == '?'
                    || str[i - 1] == pattern[j - 1])
                lookup[i][j] = lookup[i - 1][j - 1];

            // If characters don't match
            else
                lookup[i][j] = false;
        }
    }

    return lookup[n][m];
}

int main()
{
    char pattern[] = "ajjajodojei*";
    char str[] = "ahdisahdisha";
    
    

    if (strmatch(str, pattern, strlen(str),
                strlen(pattern)))
        cout << "Yes" << endl;
    else
        cout << "No" << endl;

    return 0;
}

标签: c++memset

解决方案


我不确定这种损坏的语法起源于何处,但这不是您在 C++ 中对对象进行零初始化的方式。这就是你的做法:

bool lookup = {}; // note there's no false randomly thrown in there

另请注意,上面不是数组,因为您的 VLA 在 C++ 中无效。

你的memset电话也被打破了,因为第二个参数不是 a bool,它是一个int被解释为 的unsigned char。只需阅读文档即可轻松解决这两个问题。

在 C++ 中正确定义数组的一些方法:

// nested vectors. This has the advantage of packing your values as bits instead of bytes.
std::vector<std::vector<bool>> arr;

// nested arrays stored as unique pointers. This has the advantage of automatic cleanup.
std::unique_ptr<std::unique_ptr<bool[]>[]> arr; 

// nested arrays stored as plain pointers. Just bad.
bool **arr;

// flat array of some kind. Use math to map your 2D index to a flat index and back.
std::vector<bool> arr;
std::unique_ptr<bool[]> arr;
bool *arr;

推荐阅读