Arrays 删除for循环中的数组元素-for循环跳过下一个条目的问题
为了从标题继续,我删除了for循环中数组的一个元素——问题是for循环接着读取下一个元素。因为(例如)数组编号20被删除,21变为20,所以在for循环的下一个循环中,20(以前的21)现在被跳过 更详细地说: 我有一个for循环,在其中我访问数组[I]的相应元素,循环中有一个语句,如果符合条件,它将删除数组的该项(不要担心条件是什么)Arrays 删除for循环中的数组元素-for循环跳过下一个条目的问题,arrays,c,for-loop,Arrays,C,For Loop,为了从标题继续,我删除了for循环中数组的一个元素——问题是for循环接着读取下一个元素。因为(例如)数组编号20被删除,21变为20,所以在for循环的下一个循环中,20(以前的21)现在被跳过 更详细地说: 我有一个for循环,在其中我访问数组[I]的相应元素,循环中有一个语句,如果符合条件,它将删除数组的该项(不要担心条件是什么) for(i=0;i这就是您要寻找的: for(i=0;i<total;++i) { if (delete_i'th_element) {
for(i=0;i这就是您要寻找的:
for(i=0;i<total;++i)
{
if (delete_i'th_element)
{
--total;
for (int c = i; c < total; c++)
{
trilist[c] = trilist[c+1];
}
--i; // Decrement i to compensate for the increment in outer loop
}
else
{
... other code
}
}
for(i=0;我不会跳过trilist[c+1](现在已变成c),因为循环刚刚完成了数组索引的循环?你看到我的问题了吗?:)在循环体中操作循环索引可能会令人困惑。我建议使用while
循环,并仅在必要时增加索引。你能给我举个例子吗?谢谢@Bodo,我只是暂时不知道如何为循环实现此功能loop@Bodo使用而并没有什么不同租金。然后你会有一个有增量的分行,一个没有增量的分行。你仍然需要修改total
,这也是循环条件的一部分。但所有这些都是基于意见的……只需从末尾开始,然后向后走
for (int c = i; c < totaltri; c++)
{
trilist[c] = trilist[c+1];
}
for(i=0;i<total;++i)
{
if (delete_i'th_element)
{
--total;
for (int c = i; c < total; c++)
{
trilist[c] = trilist[c+1];
}
--i; // Decrement i to compensate for the increment in outer loop
}
else
{
... other code
}
}
i = 0;
while(i<total)
{
if (delete_i'th_element)
{
--total;
for (int c = i; c < total; c++)
{
trilist[c] = trilist[c+1];
}
}
else
{
... other code
++i; // Increment i when the i'th element is processed
}
}