Grupo
Arrays y Vectores en C++
Ojetivo
1. Define un array con varios valores enteros.
2. Especifica el elemento que se eliminará.
3. Recorre el array y busca el elemento.
4. Una vez encontrado el elemento, desplaza todos los elementos subsiguientes una posición a la izquierda para rellenar el espacio.
5. Tras el desplazamiento, reduce el tamaño del array (o ajusta el índice según corresponda).
6. Prueba el programa eliminando diferentes elementos del array.
Desarrolla un programa que elimine un elemento específico de un array.
Ejemplo de Código C++
Mostrar Código C++
#include <iostream> // Include iostream for input and output
using namespace std; // Use the standard namespace
// Function to remove a specific element from the array
void removeElement(int arr[], int& size, int element) {
bool found = false; // Flag to check if the element is found
// Loop through the array to find the element
for (int i = 0; i < size; i++) {
if (arr[i] == element) { // If the element is found
found = true; // Set the flag to true
// Shift all the subsequent elements one position to the left
for (int j = i; j < size - 1; j++) {
arr[j] = arr[j + 1]; // Move each element to the left
}
size--; // Decrease the size of the array
break; // Exit the loop after removing the element
}
}
if (!found) { // If the element was not found
cout << "Element not found in the array." << endl;
}
}
// Function to print the array
void printArray(int arr[], int size) {
for (int i = 0; i < size; i++) {
cout << arr[i] << " "; // Print each element of the array
}
cout << endl; // Print a newline at the end
}
int main() {
// Define an array of numbers
int numbers[] = {10, 20, 30, 40, 50};
int size = sizeof(numbers) / sizeof(numbers[0]); // Calculate the size of the array
int elementToRemove = 30; // Element to remove
cout << "Original array: ";
printArray(numbers, size); // Print the original array
// Call the function to remove the element
removeElement(numbers, size, elementToRemove);
cout << "Array after removal: ";
printArray(numbers, size); // Print the array after removal
return 0; // End of program
}
Salida
Original array: 10 20 30 40 50
Array after removal: 10 20 40 50
Comparte este ejercicio C++