Following codes are part of a Red Black Tree program which has to take item
as a char or int, so I decided to use a template class, however I don't know how to extend it through the complete program and the compiler sends me thousand errors:
The code has German names, so if it makes it easier to understand, I will translate some of them:
baum = tree
knote = node
links = left
rechts = right
rot = red
doppel = double
mittlere = middle
eltern = parent
einfuegen = insert
rs = rb = red black
Knote.hpp
#pragma once
template <class T>
class Knote {
public:
Knote(T data = 0);
bool rot;
T item;
Knote *links;
Knote *rechts;
Knote *eltern;
};
Knote.cpp
#include "Knote.hpp"
Knote<int>::Knote(int data)
{
this->item = data;
eltern = nullptr;
links = nullptr;
rechts = nullptr;
rot = true;
}
now how should I do it for the rest?
Baum.hpp
#pragma once
#include "Knote.hpp"
#include <vector>
class Baum
{
public:
Baum();
void einfuegen(int x);
void ausgabe_levelorder();
void ausgabe_inorder();
private:
Knote<int>* head;
void rs_einfuegen(Knote<int>* &knote, Knote<int>* &eltern, int x, bool sw);
int rot(Knote<int>* &knote);
void links_rotation(Knote<int> * &links_knote);
void rechts_rotation(Knote<int> * &links_knote);
void levelorder(Knote<int>* knote, std::vector<Knote<int>*> &knoteQueue, int niveau, std::vector<int> &niveauQueue);
void sort_levelorder(std::vector<Knote<int>*> &knoteQueue, std::vector<int> &niveauQueue);
void inorder(Knote<int>* knote);
};
Baum.cpp
#include "Baum.hpp"
#include <iostream>
using namespace std;
Baum::Baum()
{
...
}
// XXX
void Baum::einfuegen(int x)
{
...
}
// XXX
int Baum::rot(Knote<int>* &knote)
{
...
}
// XXX
void Baum::rs_einfuegen(Knote<int> *& knote, Knote<int> *&eltern, int x, bool sw)
{
...
}
// XXX
void Baum::links_rotation(Knote<int>* &links_knote)
{
...
}
// XXX
void Baum::rechts_rotation(Knote<int>* &rechts_knote)
{
...
}
// XXX
void Baum::ausgabe_levelorder()
{
...
}
// XXX
void Baum::levelorder(Knote<int>* knote, vector<Knote<int>*> &knoteQueue, int niveau, vector<int> &niveauQueue)
{
...
}
// XXX
void Baum::sort_levelorder(vector<Knote<int>*> &knoteQueue, vector<int> &niveauQueue)
{
...
}
// XXX
void Baum::ausgabe_inorder()
{
inorder(head->rechts);
cout << endl;
}
// XXX
void Baum::inorder(Knote<int>* knote)
{
if (knote != nullptr)
{
inorder(knote->links);
cout << knote->item << " ";
inorder(knote->rechts);
}
}
Don't need to use Knote<T>
in the class. Just use Knote
. Instead of
Knote<T> *links;
Knote<T> *rechts;
Knote<T> *eltern;
just use:
Knote *links;
Knote *rechts;
Knote *eltern;
When you use the class template, make sure you provide a template parameter.
Knote* head;
is not right. You need to use
Knote<int>* head;
or
Knote<char>* head;
You pick the type that is appropriate for Baum
.
Move the implementation of Knote
to the .h file from the .cpp file. See Why can templates only be implemented in the header file?.