A few days ago I start learning C++. This code is a simple Union-Find data structure.
Questions:
- Why can't I use
const union_find<T> &uf
instead ofunion_find<T> &uf
? - Is it possible to replace
union_find<T>
with something likeself<T>
(self
refers to current class)? - Did I use references instead of pointers in the right places?
union_find.cpp:
template<class T>
class union_find {
public:
union_find(const T &obj) {
_parent = this;
_obj = obj;
}
void merge(union_find<T> &uf) {
_parent = &uf;
}
T find() {
union_find<T> *root = _parent;
while (root != root->_parent) {
root = root->_parent;
}
return root->_obj;
}
private:
T _obj;
union_find<T> *_parent;
};
main.cpp:
#include <iostream>
#include <string>
#include "union_find.cpp"
int main() {
union_find<std::string> foo("foo");
union_find<std::string> bar("bar");
union_find<std::string> baz("baz");
bar.merge(foo);
std::cout << foo.find() << std::endl; // foo
std::cout << bar.find() << std::endl; // foo
std::cout << baz.find() << std::endl; // baz
return 0;
}