Simple tree structure using vectors. Looking for feedback

Hello. I've implemented a simple tree structure for a computer vision project. It's the first time I've done anything serious in c++ so I would very much appreciate any kind of feedback you can think of :). Especially I would like to know if there is a simpler way to achieve the same thing (perhaps with in-built functions - or without using vectors) and if I'm doing anything that is bad form.

The idea is that the the constructor of tree_node takes in and recursively pareses a text file to construct a tree. Each line in the txt file specifies the parent node followed by its children nodes (in depth-first order). So for example if "treefile.txt" contains the following:
0 1 2
1 11 12
2 21 22 23

you should get tree where the root node "0" has two children "1" and "2" that each have 2 ("11","12") and 3 ("21","22","23") children respectively. The output of walk_depth_first() would then be:
0
1
11
12
2
21
22
23


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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
#include <iomanip>
#include <iostream>
#include <vector>
#include <fstream>
#include <sstream>

using namespace std;



struct tree_node
{
    string name;
    vector<tree_node> children;

    tree_node(string, ifstream*);
    void walk_depth_first();
};

tree_node::tree_node(string name_, ifstream* labelStream){
    name = name_;
    string labelName;
    string line;

    int pos = labelStream->tellg();
    getline(*labelStream, line);

    stringstream lineStream(line);
    lineStream >> labelName;
    int i;
    if (labelName == name){
        while(lineStream >> labelName){
            children.push_back(tree_node(labelName, labelStream));
        }
    }
    else labelStream->seekg(pos);
}

void  tree_node::walk_depth_first()
{
    cout << name << endl;
    for (int n = 0; n < children.size(); n++){
        children[n].walk_depth_first();
    }
}


int main()
{
    ifstream labelStream("treefile.txt");
    tree_node labels("0", & labelStream);

    cout << endl << "walking depth first" << endl;
    labels.walk_depth_first();
    return 0;
}
Last edited on
Topic archived. No new replies allowed.