您好,欢迎访问一九零五行业门户网

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
结束如果
example 的中文翻译为:示例#include <iostream>#include <algorithm># define z 30using 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 7array after deleting element from index 7: 56, 21, 32, 74, 96, 85, 41, 94, 20, 37, 36, 75,
结论我们在本文中展示了如何从数组中删除元素。这是一个通用过程,我们可以从任何我们喜欢的地方删除,包括开始、结束和中间。没有使用向量,因为我们没有使用任何库函数。对于动态大小的数组,基于向量的方法也是一种选择。
以上就是c++程序删除数组中的元素,不使用库函数的详细内容。
其它类似信息

推荐信息