Ok, you have a few problems. They’re all easy to fix. :O)
(1)
You are abusing “NULL”.
In C++, use
nullptr. But if you
must use
NULL, make sure it is only used to initialize
pointers.
This is actually the reason for the failure.
1 2 3 4 5
|
template <class T>
class Node
{
public:
Node<T>(T Data = T()/*NULL*/); // <-- when T is a std::string, you cannot assign it a value of NULL
|
When you run your program, the console should print something useful like:
terminate called after throwing an instance of 'std::logic_error'
what(): basic_string::_M_construct null not valid |
(You
are running this stuff from the console, right?)
(2)
You are not properly initializing the List.
1 2 3 4 5 6 7
|
template<class T>
/*inline*/ List<T>::List() :Node<T>()
{
this->head = nullptr;
this->tail = nullptr;
/*int*/ size = 0/*NULL*/; // <-- a local variable is NOT the same as the class variable with the same name
}
|
Be sure to test for all possibilities... Every time you write a function, use it in every possible combination with the other functions, and make sure your list looks like it ought after every test.
Yep. I know it is a pain in the nose.
(3)
In List<T>::search(), you re-declare the variable “newNode”:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
|
template<class T>
/*inline*/ int List<T>::search(T Data)
{
if (size == 0/*NULL*/)
{
return -1;
}
int index = 0/*NULL*/;
Node<T>* newNode = head;
while (newNode->Data != Data)
{
index++;
newNode = newNode->Next;
if (newNode == nullptr)
{
return -1;
}
}
/*Node<T>* */newNode = tail;
while (newNode->Data != Data)
{
index++;
newNode = newNode->Prev;
if (newNode == nullptr)
{
return -1;
}
}
return index;
}
|
Either re-use the variable (as I did here) or give it a different name. (The current name does not really match what the variable is used for...)
(4)
You are abusing
inline.
Modern compilers don’t really need the hint, but that is all it is — a hint.
Unless your function is
very simple, and less than maybe two or three lines of code maximum, don’t use
inline.
It doesn’t hurt to have it there, though.
Your code is otherwise very clean and well-organized.
Good job!