So, the problem presented is,
Look at the code below – it's a skeleton of a program operating on the dynamic collection of data.
The idea is to use a structure containing two fields: the first stores the number of elements in collections, and the second is the actualcollection (a dynamically allocated vector of ints).
As you can see, the collection is filled with the required amount of pseudo-random data.
Unfortunately, the program requires completion, as the most important function, intended to add elements to the collection, is still empty.
Here's what we expect from the function:
if the collection is empty, it should allocate a one-element vector and store a new value in it;
if the collection is not empty, it should allocate a new vector with a length greater by one than the current vector, then copy all elements from the old vector to the new one, append a new value to the new vector and finally free up the old vector.
I'm not hoping for the solution or anything but a pointer in the right direction would be greatly appreciated.
I've been tinkering at it for a while, and managed to get it to at least make array larger by one, but it only ever seems to copy over the location of the first value.
My code is just the stuff under AddToCollection, by the by.
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
struct Collection {
int elno;
int *elements;
};
void AddToCollection(Collection &col, int element) {
// Insert your code here
if(col.elements != NULL) {
col.elno = sizeof(col.elements);
++col.elno;
int *jeffry = new int[col.elno + 1];
jeffry[col.elno] = element;
for (int f = 0; f < (col.elno - 1); f++) {
jeffry[f] = col.elements[f];
}
col.elements = jeffry;
}
if(col.elements == NULL){
col.elements =new int[element];
}
}
void PrintCollection(Collection col) {
cout << "[ ";
for(int i = 0; i < col.elno; i++)
cout << col.elements[i] << " ";
cout << "]" << endl;
}
int main(void) {
Collection collection = { 0, NULL };
int elems;
cout << "How many elements? ";
cin >> elems;
srand(time(NULL));
for(int i = 0; i < elems; i++)
AddToCollection(collection, rand() % 100 + 1);
PrintCollection(collection);
delete[] collection.elements;
return 0;
}