如何删除数组列表中的元素
How do you remove an element in an array list
我正在将元素列表读取到数组中,然后插入一个元素,然后删除一个元素。我已经让我的代码可以很好地插入一个元素。我也让它删除了我想要的元素,但它在删除后只会输出一个元素。
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;
}
}
我希望删除元素之后的元素在列表中向上移动 1。删除元素之后的下一个元素确实向上移动,但之后的其余元素不会输出。我没有编译器错误。
这有一个错误:
while (where < numlist && id > list[where].id) where++;
if (list[where].id == id)
{
…
如果在 while 循环结束时where == numlist
(因为找不到id
指定的元素(,则list[where]
是数组中的无效位置,检查list[where].id
是不安全的。
更好:
while (where < numlist && id > list[where].id)
where++;
if ((where < numlist) && (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;
}
}
相关文章:
- C++如何通过用户输入删除列表元素
- 通过动态分配插入列表元素
- 用于编织链接列表元素的Runner Technique
- 无法在C 中删除列表元素
- 如何在不使用循环或迭代器的情况下检查所有列表元素并在满足条件时删除一个
- 将列表元素移动到列表末尾的函数多次不起作用
- 交换链接列表元素
- 当删除列表元素时,在迭代器结束时会发生什么
- 为什么从不同分配器的列表中剪辑列表元素时会有错误消息?以及如何解决
- 打印出列表元素问题
- 我想通过递归获取列表元素的所有置换
- 从C++访问列表元素 (QML) 颜色
- 如何在C++visual studio 2013中将列表元素转换为文本块
- 指向删除后的列表元素的指针
- 正在将指针复制到assign运算符中的另一个列表元素
- 将列表元素插入向量,C++获取其他不需要的值
- 从unordered_set中删除列表元素
- 在C++中打印列表元素的组件
- 提取并转换 boost::p ython::list 的列表元素
- Rcpp犰狳:对列表元素的"-="操作