Funereal
Funereal

Reputation: 673

C++ Add to the end of array

I created a pointer to pointer to a dynamic vector, is called "list".

   listaFiguras::listaFiguras(){
    numElements = 0;
    list = new figuraGeom* [numElements];

}

Here is my class too:

class listaFiguras {

    //Atributos
    int numElements;
    figuraGeom **list;

public :

    //Constructor sin parametros
    listaFiguras();

    //Destructor
    ~listaFiguras();

    //Sets y Gets
    void setnumElementos(int);
    virtual void setLista(figuraGeom**);

    int getnumElementos();
    virtual figuraGeom* getLista();

    //Vaciar lista
    void vaciarLista();

    //Añadir elemento
    void anyadirElemento(figuraGeom *);

};

Now I have to create a method called anyadirElemento but do not understand how I can do this:

Take as a parameter a pointer to figuraGeom, and added at the end of the dynamic array pointed to by list.

I got this:

void listaFiguras :: anyadirElemento (figuraGeom * parameter) {



}

Any help will be appreciated, Thanks!

Upvotes: 0

Views: 234

Answers (2)

Vlad from Moscow
Vlad from Moscow

Reputation: 310920

It would be simpler if instead of the dynamically allocated array you would use std::vector<figuraGeom *>

You have to keep the current position in the array that to know where to add a new value. For example let assume that you defined such data member of the class

int position;

and initialized it to zero some way (for example in a constructor of the class)

Then the function could look the following way provided that the array may not be reallocated

void listaFiguras :: anyadirElemento (figuraGeom * parameter)
{
   if ( position < numElements ) list[position++] = parameter;
}

So I would define data members of the class as

class listaFiguras {

    //Atributos
    int numElements;
    int position;
    figuraGeom **list;
//...

If you are allowed to enlarge the initially allocated array then the function should reallocate it each time if position is equal to numElements where numElements also will be changed or you should keep another variable that will store the current size of the array.

Upvotes: 2

Matthieu M.
Matthieu M.

Reputation: 299730

A very simple dynamic array is define as follow:

  • array size
  • pointer to array

You need to know how many elements are currently in the array to be able to use them; and when adding/removing an element you simply create another array with one less or one more element (which involves copying the old array into the new).

Note: this is extremely inefficient adding an element is O(N) where N is the number of elements already in the array but it's also very simple, in real code use std::vector<T> which performs addition at the end in amortized O(1).

Upvotes: 2

Related Questions