C++,如何让此函数删除存储在数组中的字符串
C++, How do get this function to delete the string stored in the array?
>我有一个删除函数,它应该通过用以前的字符串覆盖数组中的字符串来删除它。查看函数看到覆盖匹配并应删除。但是我在 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 foundn";
}
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 calledn";
cout<<theirArray<<endl<<endl;
您正在查找字符串,但仅在未出现时使用该值写入错误;如果您在pos N处找到该字符串,则无论如何都将删除第一个字符串:
void AR::Delete(const string & word)
{
int loc = Look(word);
if (loc == -1)
{
cout<<"word not foundn";
}
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;
不确定这是否是您的问题,但不应该这样吗?
void AR::Delete(const string & word)
{
int loc = Look(word);
if (loc == -1)
{
cout<<"word not foundn";
}
else
{
for(int i=loc;i<counter-1,i++;) // changes in this line
{
con[i]= con[i+1];
}
}
}
从找到字符串的位置开始,然后开始向后打乱它们。另外,什么缩短了数组?即删除最后一个元素。看起来也缺少了。
试试这个:
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;
}
}
相关文章:
- 使用无符号字符数组有效存储内存
- 如何在cpp.中使用协议缓冲区存储大缓冲区/数组(char/int)
- 在c++中获取两个大int,并将它们存储在数组中
- 使用 Xcode 将双精度存储在数组C++中
- 访问表示 2D 矩阵的 1D 存储数组
- 从输入文件读取整数,仅存储数组C 中的唯一整数
- 如何在队列中存储数组
- 按列主要顺序迭代行大量存储数组
- 如何使存储数组的二进制搜索稳定
- 将行中的字段从textfile中更改为存储数组,而不是重新编写文件
- 存储数组索引值C++
- 存储数组的地方,如果我在返回后声明它
- 缺少存储数组地址的内存
- 使用static在函数中存储数组各个组件的值
- 如何存储数组的每个相邻子数组的和
- 在c++中存储数组映射
- 存储数组的地址列表,以解析原始的非终止文本
- 用于存储数组的字符串
- c++存储数组下一个位置的地址
- 在 for 循环中创建和存储数组