Quiero pasar la información de un "Dynamic Array" a una "Double Linked List", mediante la creación de una función propia de cada clase. Creo que mis algoritmos para hacerlo son correctos, pero tengo problemas con la sintaxis del lenguaje.
He conseguido que una función dentro de la clase de "Double Linked List" devuelva un "Dynamic Array" con la información de la "Double Linked List", pero para ello he de comentar el código del destructor del "Dynamic Array", porque de otra forma me machaca la información antes de que la función devuelva el array, por alguna razón que desconozco.
template<class T>
DynArray<T> List<T>::dyn_array_converter() const
{
DynArray<T> newArray = DynArray<T>();
for (int i = 0; i < numElems; i++)
{
newArray.insert(i, getValue(i));
}
newArray.shrinkToFit();
return newArray;
}
Cuando ejecuto el código, el "newArray" se crea correctamente, pero cuando pasa por la línea de código "return", se ejecuta el destructor antes de devolver la variable "newArray", y a continuación me salta una excepción conforme estoy accediendo a memoria vacía. Si comento el código dentro del destructor:
template <class T>
DynArray<T>::~DynArray()
{
/*
if (arrayElems != NULL)
{
delete[] arrayElems;
arrayElems = NULL;
}*/
}
Entonces funciona, pero dudo que esa sea la manera correcta de solucionarlo. He intentado hacerlo usando punteros en lugar de variables, pero después de todo el verano desconectado no recuerdo muy bien como se usan y debo hacer algo mal, si ese es el problema me forzaré a recordar como funcionaban.
Cuando intento implementar el mismo método para pasar de "DynArray" a "Double Linked List", simplemente no compila y me da problemas con el "template". Adjunto a continuación el código entero del proyecto:
Array.h
#ifndef DYNARRAY_H
#define DYNARRAY_H
#include <assert.h>
#include <iostream>
#define min(a, b) (a < b) ? a : b
#define MIN_ARRAY_BLOCK_SIZE 10
template <class T>
class DynArray {
public:
DynArray();
DynArray(unsigned int memSize);
~DynArray();
bool empty() const;
unsigned int size() const;
bool insert(unsigned int index, const T& elem);
bool remove(unsigned int index);
T& operator[] (unsigned int index) const;
void shrinkToFit();
void print() const;
List<T> list_converter();
private:
void allocMem(unsigned int memSize);
T* arrayElems;
unsigned int memSize;
unsigned int numElems;
};
template <class T>
DynArray<T>::DynArray() :
arrayElems(NULL),
memSize(MIN_ARRAY_BLOCK_SIZE),
numElems(0)
{
allocMem(memSize);
}
template <class T>
DynArray<T>::DynArray(unsigned int memorySize) :
arrayElems(NULL),
memSize(memorySize),
numElems(0)
{
allocMem(memSize);
}
template <class T>
DynArray<T>::~DynArray()
{
/*
if (arrayElems != NULL)
{
delete[] arrayElems;
arrayElems = NULL;
}*/
}
template <class T>
bool DynArray<T>::empty() const
{
return numElems == 0;
}
template <class T>
unsigned int DynArray<T>::size() const
{
return numElems;
}
template <class T>
bool DynArray<T>::insert(unsigned int index, const T& elem)
{
// Return false if the index is out of bounds
if (index > numElems)
return false;
// If the array is full, reserve more memory
if (numElems >= memSize)
{
allocMem(memSize + MIN_ARRAY_BLOCK_SIZE);
}
// Shift elements from index one position rightwards
for (unsigned int i = numElems; i > index; --i)
{
arrayElems[i] = arrayElems[i - 1];
}
// Insert the element into the empty position
arrayElems[index] = elem;
numElems++;
return true;
}
template <class T>
bool DynArray<T>::remove(unsigned int index)
{
// Return false if the index is out of bounds
if (index >= numElems)
return false;
// Shift elements at the right of index one position to the left
// (the element at index gets overwritten/removed)
for (unsigned int i = index; i < numElems - 1; ++i)
{
arrayElems[i] = arrayElems[i + 1];
}
numElems--;
return true;
}
template <class T>
T& DynArray<T>::operator[] (unsigned int index) const
{
assert(index < numElems && "operator[] out of bounds");
return arrayElems[index];
}
template <class T>
void DynArray<T>::shrinkToFit()
{
if (numElems < memSize)
allocMem(numElems);
}
template <class T>
void DynArray<T>::print() const
{
if (numElems == 0)
{
std::cout << "Dynamic array empty" << std::endl;
}
else
{
for (unsigned int i = 0; i < numElems; ++i)
std::cout << arrayElems[i] << " ";
std::cout << std::endl;
}
}
template <class T>
void DynArray<T>::allocMem(unsigned int newMemSize)
{
// Allocate memory for the new array
T *newArrayElems = new T[newMemSize];
// Calculate the new number of elements
unsigned int newNumElems = min(numElems, newMemSize);
// Copy the old array into the new one
for (unsigned int i = 0; i < newNumElems; ++i)
newArrayElems[i] = arrayElems[i];
// Delete old array
if (arrayElems != NULL)
delete[] arrayElems;
// Assign new values
arrayElems = newArrayElems;
memSize = newMemSize;
numElems = newNumElems;
}
template<class T>
List<T> DynArray<T>::list_converter()
{
List<T> newList = List<T>();
for (int i = 0; i < numElems; i++)
{
newList.pushBack(this[i]);
}
newList.shrinkToFit();
return newList;
}
#endif
List.h
#ifndef LIST_H
#define LIST_H
#include <iostream> // std::cout and std::endl
#include <cassert> // assert
/**
* Double linked list.
*/
template <class T>
class List
{
public:
List();
~List();
void pushFront(const T& elem);
void pushBack(const T& elem);
void popFront();
void popBack();
void insert(unsigned int pos, const T& elem);
void remove(unsigned int pos);
DynArray<T> dyn_array_converter() const;
T front() const;
T back() const;
T getValue(unsigned int pos) const;
bool empty() const;
unsigned int size() const;
void clear();
void print() const;
void printReverse() const;
private:
struct node {
T value;
node *prev; // pointer to previous node
node *next; // pointer to next node
};
node *first; // pointer to the first node
node *last; // pointer to the last node
unsigned int numElems; // number of elements in the list
};
template<class T>
List<T>::List() : first(nullptr), last(nullptr), numElems(0)
{
}
template<class T>
List<T>::~List()
{
/*
clear();
*/
}
template<class T>
void List<T>::pushFront(const T& elem)
{
node *aux = new node;
aux->value = elem;
aux->prev = nullptr;
aux->next = first;
first = aux;
if (first->next)
{
first->next->prev = first;
}
if (numElems == 0) { last = aux; }
numElems++;
}
template<class T>
void List<T>::pushBack(const T& elem)
{
node *aux = new node;
aux->value = elem;
aux->prev = last;
aux->next = nullptr;
last = aux;
if (last->prev)
{
last->prev->next = last;
}
if (numElems == 0) { first = aux; }
numElems++;
}
template<class T>
void List<T>::popFront()
{
// Abort if the list is empty
assert(first != nullptr && "popFront() cannot be called if the list is empty");
node *aux = first;
first = first->next;
if (first != nullptr) { first->prev = nullptr; }
else { last = nullptr; }
delete aux;
numElems--;
}
template<class T>
void List<T>::popBack()
{
// Abort if the list is empty
assert(last != nullptr && "popBack() cannot be called if the list is empty");
node *aux = last;
last = last->prev;
if (last != nullptr) { last->next = nullptr; }
else { first = nullptr; }
delete aux;
numElems--;
}
template<class T>
void List<T>::insert(unsigned int pos, const T& elem)
{
if (pos == 0)
{
pushFront(elem);
}
else if (pos == numElems) // position after the last node
{
pushBack(elem);
}
else
{
// Abort if the position is out of the bounds of the list
assert(pos < numElems && "insert() needs a position within the bounds of the list");
unsigned int count = 0;
node *iterator = first;
while (count < pos)
{
iterator = iterator->next;
count++;
}
node *aux = new node;
aux->value = elem;
aux->prev = iterator->prev;
aux->next = iterator;
aux->prev->next = aux;
aux->next->prev = aux;
numElems++;
}
}
template<class T>
void List<T>::remove(unsigned int pos)
{
if (pos == 0)
{
popFront();
}
else if (pos == numElems - 1)
{
popBack();
}
else
{
// Abort if the position is out of the bounds of the list
assert(pos < numElems && "remove() needs a position within the bounds of the list");
unsigned int count = 0;
node *iterator = first;
while (count < pos)
{
iterator = iterator->next;
count++;
}
iterator->prev->next = iterator->next;
iterator->next->prev = iterator->prev;
delete iterator;
numElems--;
}
}
template<class T>
T List<T>::front() const
{
// Abort if the list is empty
assert(first != nullptr && "The list is empty");
return first->value;
}
template<class T>
T List<T>::back() const
{
// Abort if the list is empty
assert(first != nullptr && "The list is empty");
return last->value;
}
template<class T>
T List<T>::getValue(unsigned int pos) const
{
// Abort if the list is empty
assert(pos < numElems && "Position out of bounds");
unsigned int count = 0;
node *iterator = first;
while (count < pos && iterator->next != nullptr)
{
iterator = iterator->next;
count++;
}
return iterator->value;
}
template<class T>
bool List<T>::empty() const
{
return numElems == 0;
}
template<class T>
unsigned int List<T>::size() const
{
return numElems;
}
template<class T>
void List<T>::clear()
{
node *iterator = first;
while (iterator != nullptr)
{
node *aux = iterator;
iterator = iterator->next;
delete aux;
}
first = nullptr;
last = nullptr;
numElems = 0;
}
template<class T>
void List<T>::print() const
{
node *iterator = first;
if (iterator == nullptr)
{
std::cout << "The list is empty";
}
else
{
std::cout << iterator->value;
iterator = iterator->next;
}
while (iterator != nullptr)
{
std::cout << " <-> " << iterator->value;
iterator = iterator->next;
}
std::cout << std::endl;
}
template<class T>
void List<T>::printReverse() const
{
node *iterator = last;
if (iterator == nullptr)
{
std::cout << "The list is empty";
}
else
{
std::cout << iterator->value;
iterator = iterator->prev;
}
while (iterator != nullptr)
{
std::cout << " <-> " << iterator->value;
iterator = iterator->prev;
}
std::cout << std::endl;
}
template<class T>
DynArray<T> List<T>::dyn_array_converter() const
{
DynArray<T> newArray = DynArray<T>();
for (int i = 0; i < numElems; i++)
{
newArray.insert(i, getValue(i));
}
newArray.shrinkToFit();
return newArray;
}
#endif //LIST_H
Main
#include<stdio.h>
#include<iostream>
#include <assert.h>
#include "Array.h"
#include "List.h"
//List into DynArray
List<int> list;
list.pushFront(1);
list.pushFront(2);
list.pushFront(3);
list.pushFront(4);
list.pushFront(5);
list.print();
DynArray<int> dynarray = list.dyn_array_converter();
dynarray.print();
return 0;
}
Muchas gracias por adelantado a cualquiera que me ayude.
DynArray<T> newArray = DynArray<T>();
, en C++ no nesesitas especificar el constructor, a menos que sea un puntero, ya que se ejecuta ni bien lo nombras. Entonces seriaDynArray<T> newArray;
y numero dos, ya que estas usando tus propios objetos, olvidate de suponer que los operadores que existen ya estan sobrecargados y funcionan, no lo hacen, tienes que implementarlo todo tu.