删除数组中的记录

时间:2011-01-30 23:21:15

标签: c++

int i;
int Input;

cin >> Input;

 for(i = 0; i < Size ; i ++ )
  if (List[i].PersonID == Input) {

 }

我正在尝试创建一个函数,根据提供的id输入从数组中删除记录。我不知道在这之后该做些什么。删除记录后,是否还需要移动数组中的值?

4 个答案:

答案 0 :(得分:1)

我无法确定您的列表的类型。 但你应该这样做:

List.RemoveAt(i--);
List.DeleteAt(i--);

i--在调用函数后会减少。

如果使用标准容器,则不需要在数组中移动任何值。 如果您负责数组,那么您需要转移您的值。

**编辑

这是标准容器介绍的link。如果您正在管理自己的动态数组,则应考虑使用它们。

答案 1 :(得分:1)

这里我假设Listint s的原始数组。

#include<algorithm>  // where std::remove() resides
#include<iterator>   // where std::distance() resides (not strictly necessary)

struct BadPerson {
    BadPerson(int Bad) : Bad_(Bad) { }
    bool operator()(const Element& Elem) const {
        return Elem.PersonID == Bad_;
    }
};

// ...
int *NewEnd = std::remove_if(List, List + ListLength, BadPerson);

// the list now has a new end, because elements were "removed".
// but they weren't really removed; the array still has the same fixed size.
int ListLength = std::distance(List, NewEnd);

答案 2 :(得分:0)

我认为从数组/向量中删除元素的最佳方法是使用类似的复制方法:

int write_ptr = 0;
for (int read_ptr=0; read_ptr < n; read_ptr++)
{
    if (... keep element array[write_ptr] ? ...)
    {
        if (read_ptr != write_ptr)
            array[write_ptr] = array[read_ptr];
        write_ptr++;
    }
}
// The new size of the array is write_ptr

这样只需一次通过即可删除多个元素。

标准库将此方法包含为std::remove_if,但是在C ++ 0X到达之前由于语言的限制而使用起来很烦人(需要能够指定测试的代码变得非常难看)。

答案 3 :(得分:0)

int i;

int Input;

cin >> Input;

 for(i = 0; i < Size ; i ++ )
 {
   if (List[i].PersonID == Input)
   {
    for(int j=i;j<size-1;j++)
    {
     List[j]=List[j+1];
    }
 }
 }