Need data type to be string, not int

closed account (jEb91hU5)
Can anyone tell me why this code uses T as an int data type? I saw something that says it depends on what you declare your node as during compilation time. I'm just a little confused on how this works. I need the data type to be string instead of int. Let me know if this code snippit is enough for you to understand my question.

1
2
3
4
5
6
7
8
  // Binary Tree Node
template<class T>
struct Node {
    T data; //store data as key
    int count;
    Node<T>* lTree;
    Node<T>* rTree;
};
You want int nodes you say
 
Node<int> myIntNode;


You want strings, say
 
Node<std::string> myStringNode;

A “template” is instructions to the compiler on how to write code for you.

So, you could write a whole bunch of node classes:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
struct IntNode {
    int data;
    int count;
    IntNode* left;
    IntNode* right;
};

struct StringNode {
    std::string data;
    int count;
    StringNode* left;
    StringNode* right;
};

...

On top of that are all the functions and methods that work over every kind of node, and before long you have a gazillion lines of code all repeating themselves, where the only difference between them is the type of thing being stored in the node.

And then you discover you want to use a binary tree to store a struct point, or some other thing that you never considered when you wrote the node classes.


C++ gets rid of that mess with templates. Write a single templated class to tell the compiler how to write a specific, concrete class for whatever data type you want:

1
2
3
4
5
6
7
template <typename DataType>
struct Node {
    DataType data;
    int count;
    Node<DataType>* left;
    Node<DataType>* right;
};

The “DataType” (or “T” or whatever you name it) is a placeholder for the type you wish to abstract. That is what the compiler will replace when it writes code for you.

Thereafter you can create a binary tree using any type of data you wish, even stuff that you never thought of when you were writing the template:

1
2
3
4
Node<int>*         int_tree    = nullptr;
Node<std::string>* string_tree = nullptr;
Node<point>*       point_tree  = nullptr;  // whatever struct point looks like, you still get a valid binary tree class
// and so on 

Hope this helps.
Last edited on
closed account (jEb91hU5)
Can you show me how to implement this? Would this be inside the struct? And how does the data type of T correlate? I think I get how this is setting the data types of the nodes.
closed account (jEb91hU5)
Hahaha! I'm sorry. I totally missed the simplest thing in main. I totally get it now. Thanks for all the help.
Topic archived. No new replies allowed.