So I've got to do a project, where I need to implement an array
, a list
, binary heap
, binary tree
and a red-black tree
and then measure their performance, compare them and draw some conclusions. Now, the rules are like this:
- Got to use C/C++
- Cannot use
std::
(onlycout
, maybe astring
),Boost
So I am on a first step, implementing an array. It looks like this:
array.h
#pragma once
#include <iostream>
class array
{
int elements;
int *table;
public:
array();
array(int *t, int n);
int size() const;
int *get() const;
};
array.cpp
#include "array.h"
array::array(int *t, int n) : elements(n), table(new int[elements])
{
memcpy(table, t, elements * sizeof(int));
}
int array::size() const
{
return elements;
}
int *array::get() const
{
return table;
}
The program basically has a menu-like structure, using simple switch
and 5 different menus for 5 conteners. Now, I have to implement deleting/adding elements, printing out the array, etc. I have a code that will print out the array in one line:
int *p = myArray.get();
int s = myArray.size();
std::cout << "[";
for (int i = 0; i < myArray.size(); i++)
{
if (s - i == 1) std::cout << *(p + i) << "]" << '\n';
else std::cout << *(p + i) << ", ";
}
delete p;
The thing I am curious about is the last line I wrote. Firstly I didn't use delete
, cuz nowhere in this block of code exists a new
operator. But then I thought, yeah well, it prolly causes memory leaks, and I've added that line. Works both ways. And my question is: Which one is correct? In this situation do I have or should I delete a pointer
?