0

我有一个删除函数,它应该通过用以前的字符串覆盖它来删除数组中的一个字符串。Look 函数看到 Overide 匹配并应该被删除。但是我为 Delete 中的循环编写的代码并没有删除 Overide 占用的数组中的第一个点,并且输出保持不变。此外,+ 之后的每个短语都被添加到数组中,因此在数组中占据了四个位置,抱歉,我无法使该部分看起来更好,格式搞砸了。

int AR::Look(const std::string & word)
{
    int result = -1;
    for(int i=0; i<counter; ++i)
    {
        if( con[i].find(word) != std::string::npos)
            result = i;
    }
    return result;
}

void AR::Delete(const string & word)
{
    int loc = Look(word);

    if (loc == -1)
    {
         cout<<"word not found\n";
    }
    else
    {
         for(int i=0; i<counter-1,i++;)
         {
             con[i]= con[i+1];
         }
    }
}    



AR their

    Ar(1);
        theirAr + "Overload the +" + " operator as a member function " + "with chaining to add a string " + "to an Arrary object.";

        cout<<theirAr<<endl<<endl;


        cout<<"testing Delete and Look.  <<endl;

        theirAr.Delete("XXXXXX");
        theirAr.Delete("Overload");
        cout<<"Output after Delete and Look called\n";
        cout<<theirArray<<endl<<endl;
4

3 回答 3

0

您正在定位字符串,但如果它没有出现,则仅使用该值写入错误;如果您在 pos N 处找到字符串,则无论如何都会删除第一个字符串:

void AR::Delete(const string & word)
{
    int loc = Look(word);

    if (loc == -1)
    {
        cout<<"word not found\n";
    }
    else
    {
        for(int i=0;i<counter-1,i++;)  <--- Why don't you use loc here???
        {
            con[i]= con[i+1];
        }
    }
}

此外,您的Look方法会更好地在第一场比赛后返回:

for ... {
 if( con[i].find(word) != std::string::npos)
     return i;
}
return -1;
于 2013-09-18T21:22:51.720 回答
0

不确定这是否是您的问题,但不应该是这样吗?

void AR::Delete(const string & word)
{
    int loc = Look(word);

    if (loc == -1)
    {
         cout<<"word not found\n";
    }
    else
    {
        for(int i=loc;i<counter-1,i++;)  // changes in this line
        {
           con[i]= con[i+1];
        }
    }
}    

从找到字符串的位置开始,然后开始将它们向后移动。另外,什么缩短了数组?即删除最后一个元素。好像也少了这个。

于 2013-09-18T21:23:57.303 回答
0

试试这个:

int AR::Look(const std::string & word)
{
    for (int i = 0; i < counter; ++i)
    {
        if (con[i].find(word) != std::string::npos)
            return i;
    }
    return -1;
}

void AR::Delete(const string & word)
{
    int loc = Look(word);

    if (loc == -1)
    {
         cout << "word not found" << endl;
    }
    else
    {
         for (int i = loc+1; i < counter; ++i)
         {
             con[i-1] = con[i];
         }
         --counter;
    }
}    
于 2013-09-18T21:26:55.580 回答