如何从结构数组中删除一个数据行?(带索引)
How to delete one data line from a structure array ? (with index)
我正在尝试创建一个函数,它从结构数组中删除一行,我给函数我要删除的行的索引和结构数组。例如,我们有结构阵列:
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++设计一个数据结构
- 是否可以将多个结构作为一个数据包存储在一个函数中,然后传递给其他函数并在那里提取?
- 在结构向量中搜索一个数据成员,然后打印匹配的所有数据成员
- 如何在STD :: MAP中找到具有至少一个数据成员等于密钥的结构的元素
- 如何在不重写整个视频文件的情况下仅替换流中的一个数据框架?(ffmpeg)
- 为什么OpenDDS在删除DataWriter时重新发送相同的最后一个数据
- CAD程序的数据结构.鼠标拾取和渲染一个数据
- 提升ASIO TCP,为什么我不能在服务器端只有一个数据套接字可以打开和关闭
- 参考数据会在const函数中更改另一个数据成员
- 如何将多条字符浸入一个数据位置
- 让 pthread 等待另一个数据
- Winsock2 tcp/ip-一些数据包被忽略,可能是由于前一个数据包的null终止符
- 一个数据包的boost示例::asio
- 在C/C++中创建一个R数据帧
- 如何从结构数组中删除一个数据行?(带索引)
- QUdpsocket在处理前一个数据报时丢失数据报
- c++声明一个数据类型的字节数组,该数组存储在字符串中
- 并集:从并集的一个数据成员中读取数据,然后写入另一个
- 我可以初始化一个数据成员,这些成员本身就是头文件中的类