C++程序中删除给定索引范围[L-R]内的数组元素
在本教程中,我们将学习如何删除给定范围内的元素。让我们看看解决这个问题的步骤。
初始化数组和范围,从中删除元素。
初始化一个新的索引变量。
迭代数组。
如果当前索引不在给定范围内,则使用新的索引变量更新数组中的元素
递增新索引。
返回新的索引。
示例
让我们看看代码。
#include <bits/stdc++.h>
using namespace std;
int deleteElementsInRange(int arr[], int n, int l, int r) {
int i, newIndex = 0;
for (i = 0; i < n; i++) {
// adding updating element if it is not in the given range
if (i <= l || i >= r) {
arr[newIndex] = arr[i];
newIndex++;
}
}
// returing the updated index
return newIndex;
}
int main() {
int n = 9, l = 1, r = 6;
int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
int updatedArrayLength = deleteElementsInRange(arr, n, l, r);
for (int i = 0; i < updatedArrayLength; i++) {
cout << arr[i] << " ";
}
cout << endl;
return 0;
}输出
如果执行上述程序,您将得到以下结果。
1 2 7 8 9
结论
如果您在本教程中有任何疑问,请在评论区提出。
广告
数据结构
网络
关系数据库管理系统(RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP