C++ 如何删除数组列表中的元素
我在数组中读取元素列表,然后插入一个元素,然后删除一个元素。我已经获得了插入元素的代码。我还让它删除了我想要的元素,但它只会在删除后输出一个元素C++ 如何删除数组列表中的元素,c++,arraylist,C++,Arraylist,我在数组中读取元素列表,然后插入一个元素,然后删除一个元素。我已经获得了插入元素的代码。我还让它删除了我想要的元素,但它只会在删除后输出一个元素 void deletelist(listtype list[], int& numlist, int id, ofstream& outf) { int i, where; where = 0; while (where < numlist && id > list[where].i
void deletelist(listtype list[], int& numlist, int id, ofstream& outf)
{
int i, where;
where = 0;
while (where < numlist && id > list[where].id) where++;
if (list[where].id == id)
{
while (where < numlist - 1)
{
list[where] = list[where + 1];
list[numlist] = list[numlist - 1];
numlist--;
}
}
else
{
outf << "The item doesn't appear to be in the list" << endl;
}
}
void deletelist(列表类型列表[],int&numlist,int-id,流和流出)
{
int i,其中;
式中=0;
while(wherelist[where].id)where++;
if(列表[where].id==id)
{
while(其中
while (where < numlist && id > list[where].id) where++;
if (list[where].id == id)
{
…
但这可能不是你唯一的错误
您没有说明数组是否进行了最终排序,也没有指出numlist
是否应该在函数返回之后
我的想法是假设列表没有排序。numlist
应该反映列表的新大小。在删除的情况下,这将是numlist=numlist-1
。下面是一个更简单的方法:
void deletelist(listtype list[], int& numlist, int id, ofstream& outf)
{
int where = -1;
// find the element
for (int i = 0; i < numlist; i++)
{
if (id == list[i].id)
{
where = i;
break;
}
else if (list[i].id > id)
{
break;
}
}
if (where != -1)
{
// shift all the elements after "where" over by 1 position to the left
for (int j = where+1; j < numlist; j++)
{
list[j-1] = list[j];
}
// numlist reflects the new size of the list
numlist -= 1;
}
else
{
outf << "The item doesn't appear to be in the list" << endl;
}
}
void deletelist(列表类型列表[],int&numlist,int-id,流和流出)
{
int其中=-1;
//找到元素
for(int i=0;iid)
{
打破
}
}
如果(其中!=-1)
{
//将“where”之后的所有元素向左移动1个位置
对于(int j=where+1;j 我建议您学习如何使用调试器,并使用调试器逐步检查代码以了解发生了什么。这将是一项非常宝贵的编码技能。您能否解释一下您认为在每次while
循环的迭代中会发生什么?(不一定向我们解释;向“橡皮鸭”解释代码是您的一个技巧。)你说得对。我忘了在阅读列表时,元素一次插入一个。因此,当元素插入到列表中时,它们会按照id的正确顺序自动排序。因此排序是不必要的。在上述解决方案中没有排序。但是,我只是快速更改以打破最初的 当list[[i].id>id
变为真时,for
循环。第二个for
循环只需将每个项目移动到的右侧,其中从左侧移动一个。您最多只从列表中删除一个项目,因此numlist
只会减1。
void deletelist(listtype list[], int& numlist, int id, ofstream& outf)
{
int where = -1;
// find the element
for (int i = 0; i < numlist; i++)
{
if (id == list[i].id)
{
where = i;
break;
}
else if (list[i].id > id)
{
break;
}
}
if (where != -1)
{
// shift all the elements after "where" over by 1 position to the left
for (int j = where+1; j < numlist; j++)
{
list[j-1] = list[j];
}
// numlist reflects the new size of the list
numlist -= 1;
}
else
{
outf << "The item doesn't appear to be in the list" << endl;
}
}