c++ - 数组 X[n] 仅存储名称。编写算法以在数组中插入或删除 ITEM
问题描述
数组 X[n] 仅存储名称。数组的第一个位置不存储名称,而是存储数组中可用空闲空间的数量。编写算法以在数组中插入或删除 ITEM。
解决方案
如果你想在一个数组中插入某个pth
位置,那么从 i 到最后一个元素的所有元素都应该移动到下一个位置(这将使大小增加)。并将所需的元素放在第 p 个位置。
//you want to insert x in the pth position of A[n]
int temp = x;
for(int i=p; i<n; i++) {
swap(temp, A[i]);
}
A[n++] = temp;
同样,要在 pth 位置删除,只需将下一个项目抓取到前一个位置并减小大小:
for(int i=p+1; i<n; i++) {
A[i-1] = A[i];
}
n--;
推荐阅读
- javascript - 调用 daterangepicker onclick
- javascript - 无法承诺基于回调的函数
- python - 根据多个值过滤字典列表
- ruby-on-rails - 在使用 Ransack 显示结果之前,在另一个页面上运行 Controller 中的方法
- unity3d - Unity 的跨平台文件浏览器
- javascript - 如何在 Apps 脚本中设置字体粗细 - Google Docs
- sql-server - 哪种数据库软件适合 Data Historian?
- python - 无法使用 streamParse “thriftpy.thrift.TApplicationException:内部错误处理 beginFileUpload”提交拓扑
- r - 在固定字符位置之前提取字符串
- angular - 在 Angular 中,您如何从只能选中一个复选框的用户变为多个复选框?