C++程序:在不使用库函数的情况下从数组中删除元素
数组的目的是通过基地址和索引,在多个内存位置访问相同类型的数据。在各种各样的应用中,数组被用于存储数据,原因多种多样。与其他数据结构一样,数组必须能够有效地处理元素的添加、删除和更新。静态数组和动态数组都包含许多C++库函数,用于处理各种与数组相关的操作。但是,在本文中,我们将了解如何在不使用任何C++库函数的情况下从数组中删除元素。
通过示例理解概念
Given array A = [89, 12, 32, 74, 14, 69, 45, 12, 99, 85, 63, 32] After deleting an element from index 5, the array will be like this: A = [89, 12, 32, 74, 14, 45, 12, 99, 85, 63, 32]
从任意位置删除元素,有三种可能的情况。从开头删除、从结尾删除以及从任意索引的中间删除。从结尾删除不需要任何移位操作。但其余两种情况需要将元素向左移位。首先从该位置移除元素,然后用后续元素填充该位置。让我们看看算法和C++代码,以便更好地理解。
算法
获取包含n个元素的数组A和位置pos
如果pos >= n + 1,则
无法删除,退出函数
否则
对于索引c = pos到n − 1,执行
A[ c ] = A[ c + 1 ]
结束循环
n := n − 1
结束if
示例
#include <iostream>
#include <algorithm>
# define Z 30
using namespace std;
void displayArr(int arr[], int n ) {
for( int i = 0; i < n; i++ ){
cout << arr[ i ] << ", ";
}
cout << endl;
}
void deleteElement( int A[], int &n, int pos ){
if ( pos >= n + 1 ) {
cout << "Deletion not possible" << endl;
return;
}
else
{
for ( int c = pos; c < n ; c++ ) {
A[ c ] = A[ c + 1 ];
}
n = n - 1;
}
}
int main() {
int arr[ Z ] = {84, 56, 21, 32, 74, 96, 85, 41, 21, 94, 20, 37, 36, 75, 20};
int n = 15;
cout << "Given array elements: ";
displayArr( arr, n);
cout << "Delete from last position (position 15)" << endl;
deleteElement( arr, n, 15 );
cout << "Array after deleting last element: " << endl;
displayArr( arr, n);
cout << "Delete from first position (position 0)" << endl;
deleteElement( arr, n, 0 );
cout << "Array after deleting first element: " << endl;
displayArr( arr, n);
cout << "Delete from position 7" << endl;
deleteElement( arr, n, 7 );
cout << "Array after deleting element from index 7: " << endl;
displayArr( arr, n);
}
输出
Given array elements: 84, 56, 21, 32, 74, 96, 85, 41, 21, 94, 20, 37, 36, 75, 20, Delete from last position (position 15) Array after deleting last element: 84, 56, 21, 32, 74, 96, 85, 41, 21, 94, 20, 37, 36, 75, Delete from first position (position 0) Array after deleting first element: 56, 21, 32, 74, 96, 85, 41, 21, 94, 20, 37, 36, 75, Delete from position 7 Array after deleting element from index 7: 56, 21, 32, 74, 96, 85, 41, 94, 20, 37, 36, 75,
结论
在本文中,我们演示了如何从数组中删除元素。这是一个通用过程,我们可以从任何我们想要的位置删除元素,包括开头、结尾和中间。由于我们没有使用任何库函数,因此没有使用向量。对于动态大小的数组,基于向量的方法也是一种选择。
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP