int i;
int Input;
cin >> Input;
for(i = 0; i < Size ; i ++)
if (List[i].PersonID == Input) {
}
我想做一个函数,根据提供的id输入从数组中删除记录。我不确定在这里做什么以外。在删除记录后,我还需要移动数组中的值吗?删除阵列中的记录
int i;
int Input;
cin >> Input;
for(i = 0; i < Size ; i ++)
if (List[i].PersonID == Input) {
}
我想做一个函数,根据提供的id输入从数组中删除记录。我不确定在这里做什么以外。在删除记录后,我还需要移动数组中的值吗?删除阵列中的记录
我不知道你的列表是什么类型。 但你应该去这样的事情:
List.RemoveAt(i--);
List.DeleteAt(i--);
我 - 会递减之后我的函数被调用。
如果您使用的是标准容器,则不需要移动数组中的任何值。 如果您对数组负责,那么您确实需要改变数值。
**编辑
这里是一个link到介绍的标准容器中。如果你正在管理你自己的动态数组,你应该考虑使用它们。
这里我假设List
是一个原始数组int
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);
我想从一个阵列/矢量删除元素,最好的办法是使用副本的方式与类似:
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到达为止,由于语言的限制(需要能够指定测试的代码变得非常难看),令人讨厌使用。
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];
}
}
}
List是什么类型? – 2011-01-30 23:29:15
该类型是int。 – F100 2011-01-30 23:34:02
`List`很可能是* not *`int`,而是`int`的容器,它具体是什么类型? – 2011-01-30 23:45:46