我有一个删除函数,它应该通过用前面的字符串写一个字符串来删除数组中的字符串。 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;
答案 0 :(得分: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;
答案 1 :(得分: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];
}
}
}
从找到字符串的位置开始,然后开始向后移动它们。什么缩短阵列?即关闭最后一个元素。看起来也不见了。
答案 2 :(得分: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;
}
}