数组元素的移除
- 核心思路:创建一个新的内存空间存储移除后的数组,再将原数组delete释放,再将指针指向新数组。
cout << "----------------------------- 数组元素的移除 -------------------------" << endl;
//cout << deleteArrByIndex(0, arr11) << endl;
// 示例数组
int * pArr = new int[5] {1,3,5,7,9};
int * pNewArr = new int[4];
int deleteIndex = 2; // 移除下标为2的元素
int len = 5;
for (int i = 0; i < len; ++i) {
if(i == 2) {
continue;
}
if(i <= 2) {
pNewArr[i] = pArr[i];
}else {
pNewArr[i - 1] = pArr[i];
}
}
delete[] pArr; // 回收老数组的空间
pArr = pNewArr; // 将老数组的指针指向新数组的内存空间
// 打印删除后的数组
for (int i = 0; i < 4; ++i) {
cout << pArr[i] << endl;
}
数组元素的插入
int * pArr2 = new int[]{1,2,3,4,5}; // 1 , 3下标插入 0
int * pInsert = new int[7];
int offset = 0;
for (int i = 0; i < 5; ++i) {
if(i == 1 || i == 3) {
pInsert[i + offset] = 0;
offset ++;
}
pInsert[i + offset] = pArr2[i];
}
delete[] pArr2;
pArr2 = pInsert;
for (int i = 0; i < 7; ++i) {
cout << "pArr2[" << i << "] = " << pArr2[i] << endl;
}
标签:pArr2,int,元素,C++,pInsert,++,数组,offset From: https://www.cnblogs.com/1873cy/p/18181275