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,
結論
在本文中,我們演示瞭如何從陣列中刪除元素。這是一個通用過程,我們可以從任何我們想要的位置刪除元素,包括開頭、結尾和中間。由於我們沒有使用任何庫函式,因此沒有使用向量。對於動態大小的陣列,基於向量的方法也是一種選擇。
廣告