Insert objects into an array with dynamic memory (without allowed vectors) C ++

I cannot use Vectors specifically for this school assignment. Most of the answers I found simply state that "you must use vectors" as the most voted comment. Although I appreciate and understand this, I simply cannot use them for this assignment.

This is the purpose of C ++ with dynamic memory management as follows:

// property in header declaration
int numAnimals;
int capacity;
Animal** animals; 
void addAnimal(Animal *newAnimal);

// class implementation
capacity = 10;
numAnimals = 0;

animals = new Animal*[capacity];

void SampleClass::addAnimal(Animal *newAnimal)
{
  for (int i = 0; i < capacity; i++){
       if(animals[i]){
          // animal object already exists in array, move on
          i++;
       }else{
          animals[i] = newAnimal;
          numAnimals++;
          break;
       }
   }
}

animals is a pointer to a pointer, in this case a pointer to an array of pointers to the type of the Animal object that has not yet been created.

"addAnimal" , , , , , . , .

- - , " " .

, : if (animals [i]), , , , , , , "else", - , , , , -, , .

, , ? , , , .

, , , , ++ stackoverflow . , , [], .

, !

+4
3

numAnimals , for, ( , for, , nullptr).

:

// Inside SampleClass::addAnimal(Animal *newAnimal):

animals[numAnimals] = newAnimal;
numAnimals++;

, , , .
, , , , , :

// Before inserting:
if (numAnimals == capacity) 
{
    // You ran out of capacity.
    //
    // 1. Allocate a new array with bigger capacity (e.g. 2X)
    // 2. Copy the content from the current array to the new one
    // 3. delete current array
}

:

, , delete[]

, delete[] animals, , Animal, .

+4
int capacity = 10;
Animal** animals = new Animal*[capacity];

, , , , .

if (animals[i])

nullptr, , , nullptr.

loop-pass, , :

for(int i=0; i<capacity; ++i)
    animals[i] = nullptr;

:

if (animals[i]) {
    // animal object already exists in array, move on
    i++; // <- here

, for (int i = 0; i < capacity; ++ )

+4

, " ", , , . , , , , class std::vector. .. ( , Animal ..), class, ( ) . :

template <typename T> 
class my_vector {
    private:
        T* data;
        size_t size;
        size_t capacity;
    public:
        void push_back(const T& t);
        size_t size();
        T& operator[](size_t index);
        void resize(size_t size);
        //... etc...
};
+1

Source: https://habr.com/ru/post/1687872/


All Articles