Click here to Skip to main content
15,887,214 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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 actual collection (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.
Here's what i expect from the function:
1. if the collection is empty, it should allocate a one-element vector and store a new value in it.
2. 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.

What I have tried:

C++
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;

struct Collection {
   int elno;
   int *elements;
};
void AddToCollection(Collection &col, int element) {
   //the first part of the funtion


}

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;
}
Posted
Updated 6-Feb-18 12:02pm
v2

Quote:
int *temp;
temp = new[];
Let's fix your starting point. The above statemens should be
C++
int * temp;
temp = new int[col.elno + 1];
Now your temp vector as the right number of items.

You have to
  • Copy all the col.elements items into temp.
  • Add element at the end of temp.
  • Release col.elements memory (delete it).
  • Set col.elements equal to temp.
  • Increment col.elno

That's all folks.
 
Share this answer
 
Comments
rafaelfinalcut10 4-Feb-18 17:04pm    
Thank You man you save my life
CPallini 4-Feb-18 17:09pm    
You are welcome.
As I told you when you posted this earlier today, we do not do your work for you. Deleting the question and reposting it in the hope we won't notice is not a good idea - it won't get your work done for you, but it will annoy people.

Read the instructions carefully, and think about what you need. You could easily have completed this in the time you have wasted posting this question repeatedly...
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900