如何从结构数组中删除一个数据行?(带索引)

How to delete one data line from a structure array ? (with index)

本文关键字:一个 数据 索引 结构 数组 删除      更新时间:2023-10-16

我正在尝试创建一个函数,它从结构数组中删除一行,我给函数我要删除的行的索引和结构数组。例如,我们有结构阵列:

Structure
{
string First;
string Second;
string Third;
string Fourth;
string Fifth;
}

结构阵列:

Structure A[100];
int n;

因此,在这个结构数组中有五个字符串类型的元素:

A[i].First A[i].Second A[i].Fourth A[i].Fifth // i is the index

我们的功能是这样的:

void Delete(Structure A[], int index, int & n) 
{
Structure t;
for (int i = index; i < n-1; i++)
{
    t = A[i];
    A[i] = A[i + 1];
    A[i + 1] = t;
    n--;
} 
}

所以我给函数一个索引,我希望函数用这个索引删除我的结构数组中的所有元素(那么我怎么能像这些元素的整个"行"一样,而不是一个接一个地删除它们呢?)

A[index].First A[index].Second A[index].Third A[index].Fourth A[index].Fifth

然而,该功能不起作用。你能给我一些建议吗?提前谢谢。

在第一个层次上,您的问题基本上是:如何从数组中删除一行,该数组的使用大小存储在外部变量(此处传递为n)中

您的函数的签名是正确的,而实现不是。应该是:

void Delete(Structure A[], int index, int & n) 
{
    // eventually control index >= 0 and index < n...
    n -= 1;
    for (int i = index; i < n; i++)
    {
        A[i] = A[i + 1];
    }
}

如果您有支持移动语义的C++的最新版本,您可以通过移动字符串而不是复制字符串来加快操作:

    n -= 1;
    for (int i = index; i < n; i++)
    {
        A[i] = std::move(A[i + 1]);
    }