-4

I was introduced to pointers, I quite get it. but I don't know how to store variables in the vector class using pointers.

Here is what I got from my understanding but how should I complete it?

class Vector{
    int size;       
    int* element; 

    public:
    vector(int x); 

    int size() const { return size }
};
Iva
  • 37
  • 7

2 Answers2

1

To complete what you started, you simply need to use new[] operator to allocate memory to store your int values:

vector(int x)
{
    size = x;
    element = new int[size]; // this allocates an array of int with a size of "size"
}

Then, you can use element[i] to access i's element of your array.

You'll later need (it's a must) to release allocatd memory to prevent memory leak by implementing a destructor:

~vector()
{
    delete [] element;
}

Note that you should (must) also also follow at least the rule of 3 to have you vector be copiable.

jpo38
  • 20,821
  • 10
  • 70
  • 151
1

first, you need to define a value that stores the current size - (number of elements inside the vector) - to be able to add values at the end of the vector.

int curr_vec_size;

also, the actual size of the vector should be saved in a variable to check every time you add a value that allocated memory is not full

int memory_size;

second, you need to allocate memory dynamically by using "new" in the constructor

    vector(int size)
{
    element = new int[size];        //allocating memory (array of integers)
    memory_size= size;              //size of allocated memory
    curr_vec_size= 0;               //no values in the vector 
}

then you can make a method that takes an int value and adds it to the dynamic array.

    void add_value(int passed_val)
{
    if(curr_vec_size < memory_size)
    {
        element[curr_vec_size]=passed_val;    //adding the value in the vector
        curr_vec_size ++;                     //because you have added a new value
    }
    else 
        cout<<"vector is full \n";
}

Finally, don't forget to delete the memory you've allocated by using destructors that deletes the pointer to this allocated memory.

vector()
{
   delete[] element;
}
Shaaer
  • 527
  • 5
  • 17