最好说我做错了,然后说比较不起作用。但是,我已经研究这段代码已有一段时间了。

我有一个递归函数。大部分都运行良好,因此我只介绍不起作用的部分:

//In main
string C[] = {"S=>bS",
                    "S=>aaT",
                    "T=>aT",
                    "T=>bU",
                    "U=>Ua",
                    "U=>aa"};
CFG CFG1(C);

...

string *code;
char startNT;
//The CFG constructor
CFG::CFG(string C[])
{
    code = C;
    startNT = code[0][0];
}

...

//Inside of processData recursive function
for(unsigned int i = 0; i < code->size(); i++)
{
    if(code[i][0] == startNT)
    {
        string newStr = code[i].substr(code[i].find(">")+1);
        string old = wkString;
        //This is the recursive call
        if(processData(inString, wkString.replace(wkString.find_first_of(startNT), wkString.find_first_of(startNT)+1, newStr)))
        {
            return true;
        }
        cout << wkString << endl;
        wkString = old;

    }
}


比较失败的代码是code [i] [0] == startNT。好吧...我应该说,不是100%的时间都在工作。直到递归函数执行到一半,代码[i] [0]变成“ S”,startNT变成“ T”(在已经证明它可以在调用过程中的某个地方正确比较“ S”和“ T”之后),它才有效。并且它仍然评估为true,这导致wkString.replace()中断,因为找不到'T'。

自从我使用C ++已经有一段时间了,所以我可能犯了一个愚蠢的错误。谢谢你的帮助。

最佳答案

code是指向字符串数组中第一个字符串的指针。因此,当您说code->size()时,这就是第一个字符串的大小(字符数)(在您给出的示例中为5)。我确定您要遍历字符串数组,而不是第一个字符串中的字符。这是错误的。

不幸的是,由于您将指针存储在类中,而不是数组中,因此该类不知道数组的大小。因此,您无法对其进行适当的迭代。您需要以某种方式重组代码。如果无法更全面地了解它,我将无法提出任何具体建议。

您可能想要做的是在实际的类中存储字符串集合。默认情况下,我建议使用向量。然后,您的代码可能看起来像这样:

// in class CFG
std::vector<std::string> code;
char startNT;

CFG(const string * C, int N)
    :code(C, C+N),
    startNT(code[0][0]) // strong assumption made here
{}
...
// processData
for(unsigned int i = 0; i < code.size(); i++) // note, dot instead of arrow
{
...
// in main
std::string C[] = {
    "S=>bS",
    "S=>aaT",
    "T=>aT",
    "T=>bU",
    "U=>Ua",
    "U=>aa"
};

CFG CFG1(C, sizeof(C)/sizeof(*C));

10-07 19:12
查看更多