14.7k views
4 votes
Create a function called insertArray. It should take in a number and insert it into a full array. (For instance, if the array is 1,2,3,4 you should be able to append the number 5.) Do the same with a vector (call the function insertVector).in c++

1 Answer

2 votes
Here's a C++ code example for the `insertArray` and `insertVector` functions:

```cpp
#include
#include

// Function to insert a number into an array
void insertArray(int arr[], int &size, int number) {
if (size < 100) { // Assuming a maximum array size of 100
arr[size] = number;
size++;
} else {
std::cout << "Array is full. Cannot insert." << std::endl;
}
}

// Function to insert a number into a vector
void insertVector(std::vector &vec, int number) {
vec.push_back(number);
}

int main() {
int arr[100] = {1, 2, 3, 4};
int arrSize = 4;

std::vector vec = {1, 2, 3, 4};

int numberToInsert = 5;

// Insert into the array
insertArray(arr, arrSize, numberToInsert);

// Insert into the vector
insertVector(vec, numberToInsert);

std::cout << "Array after insertion: ";
for (int i = 0; i < arrSize; i++) {
std::cout << arr[i] << " ";
}
std::cout << std::endl;

std::cout << "Vector after insertion: ";
for (int i : vec) {
std::cout << i << " ";
}
std::cout << std::endl;

return 0;
}
```

This code defines two functions, `insertArray` and `insertVector`, for inserting a number into an array and a vector, respectively. The code then demonstrates how to use these functions to insert a number into both an array and a vector.

Hope this helps! :)
User Fazineroso
by
6.9k points