Can I make a binary search tree with this? - c++

I've made BSTs before. Can I use this to make a BST without modifications?
template <class Item>
class binary_tree_node
{
public:
private:
Item data_field;
binary_tree_node *left_ptr;
binary_tree_node *right_ptr;
};
I tried making a BST with this but ran into some problems. For one thing, when I create the root node, I can't access the pointers to its child nodes.

No, you won't be able to make a BST with a class that says "place public member functions here".
It won't even compile without some pretty hacky typedefs and macros.

Without modifications, no.
But that line 'place public member functions here' is screaming out that you should be modifying it.
Since you talk about permission problem, it means you are trying to use free functions. But since the pointers are private, you won't have access to them.
What you should be doing is creating member functions. For example:
class binary_tree_node
{
public:
binary_tree_node()
{
}
bool is_item_in_tree(const Item &item)
{
}
...
};
Anyway, I'd recommend reviewing your C++ basics around visibility and OOP.

Normally,you should provide the comparation interface for the new Item class,becuase in the insert and remove opeartion,the comparation are needed.
The concrete information was not given,so I do not know whether you use < and > etc relation operators or not.But If you use them.You should make sure the new Item class support these operators.
I'd advice you to add one generic comparation class name Comp to provide the compration interface for the Item class.

Related

How to decide which methods belong where? C++

I finished writing an AVL tree, and one of the things that bothered me when programming it is deciding which methods belong to which class:
template <class ValueType,class CompareFunction>
class avlTree{
class avlTreeException{};
public:
class ElementDoesntExist : public avlTreeException{};
class EmptyTree : public avlTreeException{};
class ElementAlreadyExists : public avlTreeException{};
private:
class Node{
friend class avlTree;
ValueType* data;
Node *sonA,*sonB,*dad;
int height,balance;
private:
CompareFunction compare;
int treeSize;
Node* root;
};
(I removed the public\private methods to save space).
For some methods I think I made the right choice: update is a method of Node (updates height,etc).
Insert/remove are functions of the tree.
But for example the function destroyNodeTree(Node*) which is used by the tree destructor. What I did is to have destroyNodeList() call destroyNodeTree(root)
template <class ValueType,class CompareFunction>
void avlTree<ValueType,CompareFunction>::avlTree::destroyNodeTree(Node* rooty) {
if(!rooty){
return;
}
Node *A=rooty->sonA,*B = rooty->sonB;
destroyNodeTree(A);
destroyNodeTree(B);
}
However, I could have made destroyNodeTree() a method of Node, and call it on the root from the destructor (it would be implemented in the same way).
I had a similar issue deciding where the method findNode(const ValueType&) should go, meaning it obviously is a public method of tree, but should I create a method for Node with the same name and have the tree function call the node method on the root? Is it even acceptable to have a public function and an inner class method with the same name?
In my opinion it's better to have it as a method of nodes because that gives more flexibility (I'll be able to search for a node only under a certain node), but on the other hand that means that the method either needs to create an instance of class compare, or have each node keep a copy of an instance, or have class compare as a static function. Each of those has a disadvantage in my opinion though: creating an instance can be costly, keeping a copy can be costly, and forcing the user to make the function static doesn't seem right to me (but I'm horribly inexperienced so fix me if I'm wrong).
In any case I eventually made findNode a treeFunction only and not a method (the HW assignment didn't need the tree to able to search from a specific node so it doesn't make any difference there) but I don't want to write bad code.
To conclude, how do we decide where to save performance,memory,flexibility of the user (would he rather be able to search from any node or create nonstatic compare functions?)

Using a(n empty) base class to enable storing different objects in the same container

Say I have two different objects that are completely different, Sprite and PhysicsData.
I write an empty base class and a container class that can push and remove objects to/from a container.
I create two of these containers to store the two different objects - Sprite and PhysicsData.
(Different objects aren't together in the same class)
class base
{
};
class ContainerManager
{
public:
std::vector<base*> list;
void Push(base *object);
void Remove(base *object);
};
class PhysicsData : public base
{
void applyGravity();
};
class Sprite : public base
{
void Draw();
};
ContainerManager SpriteContainer;
ContainerManager PhysicsDataContainer;
Sprite aSprite;
SpriteContainer.Push(&aSprite);
PhysicsData SomeData;
PhysicsDataContainer.Push(&SomeData);
Is this the way that this should bet done?
This is not a C++ way. You should use templates.
For you to know, STL (which you are calling to when using std:: namespace prefix) is, actually, Standard Template Library :). A lot of template classes are already there, e.g. for the push / remove operations see std::list<T>
You use it like this:
std::list<Sprite> SpriteContainer;
std::list<PhysicsData> PhysicsDataContainer;
and so on.
There is a cool guide about C++ templates, if you still want to do your own class for some more functionality.
And there is a reference to std::list, (i don't think i need to explain the usage of std::vector for you) if the question was the actual thing you've wanted to do.
You're having Templates in C++ and still worrying about having a common base class for a trivial container??
template <class T>
class Container{
private:
vector<T> list;
public:
void Push(T data);
T Pop();
};
If you put a single virtual function into the base class, you'll be able to use dynamic_cast to get back the proper pointer if you mix different types in the same container. A virtual destructor would be a good idea because then you could delete the object if it were dynamically allocated, without having to cast it back to the original pointer.
If you're not going to mix types within a single container, I agree with dreamzor that a template class would be better. That's the way all the standard containers are implemented.
That looks like technically correct code but you are not doing any type checking. So as you can see PhysicsData is showing up in your SpriteContainer. You probably do not want this.
There is more than one way to keep PhysicsData out of your SpriteContainer. One way is to use templates. With templates you would state what type of base objects the container should work with at compile time.
Another method is to inherit from your ContainerManager two types of ContainerManagers, one called PhysicsContainerManager and one called SpriteContainerManager. These two child classes can do type check to verify that the objects being passed are in fact either a SpriteContainer or a PhisicsData. This link shows how to do type check in c++ C++ equivalent of instanceof
thanks
jose

Using generic ADTs

I have a design problem. I'm asked to plan a design for a certain problem, where I need a few lists, and also a queue (which I need to create by myself, STL isn't allowed). In order to make the implementation more efficient, I thought about creating a generic list as follows: Create a node which contains a pointer to 'Data', an empty class. Then, any class that I want to make a list or a queue of (is the last sentence grammatically correct?), I'll just make it a subclass of data. That's the only way to make a generic list (I think), as we are not allowed to use void*.
The problem begins when I want to use a certain method of a certain class in a certain list. I can't do that, since 'Data' doesn't know that function. Creating a virtual function in Data is counter-logical and ugly, and we're also not allowed to use any downcasting.
Is there a way to overcome the problem using generic ADTs? Or must I create specific lists?
Thank you very much!
edit: We are also not allowed to use templates.
About the list and the queue, maybe you can adopt the same approach taken by the STL: just create the list, and then stack, as an adaptor of the list in which you only push and pop from the end.
About those contraints, which seems to be draconian, don't I suppose that the objective is for you to use templates?
Instead of creating and empty class, which if does not contain any method does not serve you at all, use a template as in the following example:
template<typename T>
class List {
class Node {
public:
Node(T* d)
{ data.reset( new Data( d ) ); }
T * getData()
{ return data; }
Node * getSig()
{ return sig; }
private:
std::auto_ptr<T> data;
Node * sig;
};
List()...
// Lots of more things...
};
You can find more info here:
http://www.cplusplus.com/doc/tutorial/templates/
Hope this helps.

Allowing a class function to easily be replaced

I often have a class where I want to allow a functionality to be selected. For example I have a class that has a GetNextNode() function which is used like MyClass::DoIteration(){GetNextNode(); } . I want to allow the user to select from one of many possible implementations of GetNextNode to determine how the next node to process should be determined. I also want to allow a user of my code to easily provide their own implementation.
So far, the answer is to make GetNextNode() virtual and re-implement it subclasses of MyClass...
My problem arises when I have two such interchangeable functions. If I have Function1() and Function2() which both have N possible implementations, then I would have to provide 2N subclasses to allow the user to pick which pair of these functions to use. Generally, it is much worse (if there are more than 2 such functions).
Note that these functions need access to data inside MyClass.
Is there a "pattern" that I am missing that allows "plugins" like this to be selected?
Actually I think what he's looking for is Policy based design, see http://en.wikipedia.org/wiki/Policy-based_design.
EDIT:
Example, (obviously doesn't compile, but hopefully you get the idea. You provide a template parameter for IterationPolicy, and it's expected to be a class that provides a getNextNode function. You can provide a default policy and a variety of alternate policies with your class. Also the user can write their own, provided they implement the appropriate interface. Avoids the problems associated with inheritance.
template <typename IterationPolicy = DefaultIterationPolicy>
class class X {
IterationPolicy iterationPolicy;
void DoIteration() { iterationPolicy.getNextNode(); }
};
This looks like the Strategy Pattern Edit: And if you only need compile time variations, the Policy-based design you disovered yourself can be more appropriate.
class NextNodeStrategy {
public:
virtual int GetNextNode() = 0;
};
class MyClass {
private:
NextNodeStrategy &nextNode;
public:
void SetNextNodeStrategy(NextNodeStrategy &strategy)
{
nextNode = strategy;
}
void DoIteration()
{
nextNode.GetNextNode();
}
};
The strategy might need access to other stuff, so you might need to pass in something to GetNextNode, now that the implementation lives in a separte class, and you might want to provide a default implementation of it (e.g. just have MyClass inherit from NextNodeStrategy , and set nextNode = this; in the MyClass constructor.
If you have other things that also can be changed, you make a strategy out of that too, and the 2 can vary independently.
Have you looked at the visitor pattern?
You can offer the different implementations as protected functions.
...
protected:
Node GetNextNode_Method1();
Node GetNextNode_Method2();
public:
Node GetNextNode();
...
The final class can override GetNextNode() to apply one of the offered alternatives.

Keeping part of public nested class visible only to the nesting class

I have a nested class in c++ which has to be public. But I need some of its methods visible to the outer world, and the rest visible only to the nesting class. That is:
class set {
public:
class iterator {
innerMethod();
public:
outerMethod();
}
}
I want to be able to write a method for set which uses innerMethod(). If I make it public, I can access it from outside as well, which is something that I definitely don't want. Is there a way to do it without doing the "friend class set" thing?
Thanks in advance!
There is NO GOOD WAY you can do this, without using friend keyword.
In the comment you said:
In the programming class I currently
take, using 'friend' was said to be
ill-advised and generally considered
"bad programming" for the most part,
unless there is really no other way
around it. So I try to avoid it as
much as possible.
friend breaks encapsulation, maybe that is the reason why your class teacher said it's bad-programming. But member-functions too break encapsulation, then why do you use them? Why not avoid them too? friend breaks encapsulation in the same way as do member-functions; so if you're comfortable using member-functions when they're needed, then you should be comfortable using friend also when they're needed. Both exist in C++ for a reason!
class set {
public:
class iterator
{
friend class set; //<---- this gives your class set to access to inner methods!
void innerMethod(){}
public:
void outerMethod(){}
};
iterator it;
void fun()
{
it.innerMethod();
it.outerMethod();
}
};
See this : How Non-Member Functions Improve Encapsulation
No, I don't think there are other non-hacky methods but using the friend-directive.
friend exists right for this kind of purpose, why would you avoid it?
Try asking: is there any way to add 2 numbers without adding them?
Sorry if I'm harsh, but friend class is for exactly that...
Yes there is.
I've been trying to advocate the method for a while now, the basic idea is to use a Key class.
While this does not actually remove the use of friend, it does reduce the set of exposed implementations details.
class set;
// 1. Define the Key class
class set_key: noncopyable { friend class set; set_key() {} ~set_key() {} };
class set
{
// 2. Define the iterator
class iterator
{
public:
void public_method();
void restricted_method(set_key&);
}; // class iterator
}; // class set
Now, restricted_method is public, so set does not need any special access to iterator. However the use of it is restricted to those able to pass a set_key instance... and conveniently only set may build such an object.
Note that set may actually pass a set_key object to someone else it trusts. It is a key in the traditional sense: if you give a key of your flat to someone, it may entrust it to another person. However because of the semantics of the key class (non copyable, only set may construct and destroy it) this is normally limited to the duration of the scope of the key object.
Note that a evil hack is always possible, namely *((set_key*)0). This scheme protects from Murphy, not Machiavelli (it's impossible in C++ anyway).
You can do something like this:
class set
{
public:
class iterator
{
protected:
iterator(){};
virtual ~iterator(){};
public:
//outer world methods...
};
private:
class privateIterator : public iterator
{
public:
privateIterator(){};
~privateIterator(){}
//inner methods;
};
public:
iterator* CreateIterator()
{
return new privateIterator();//this is used to be sure that you only create private iterator instances
}
};
I don't know if it's the right answer, but it does now uses friend key work and it hides some of the methods. The only problem is that you can't declare privateIterator and you always must use CreateIterator to create an instance...