gpt4 book ai didi

c++ - 如何从结构数组中删除一条数据线? (带索引)

转载 作者:行者123 更新时间:2023-11-28 05:41:28 24 4
gpt4 key购买 nike

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

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]);
}

关于c++ - 如何从结构数组中删除一条数据线? (带索引),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37007180/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com