Building a n-ary tree from a map

533 views Asked by At

i was trying to build a tree out of a map, to show a class Hierachy with base classes and derrived classes. One node can have multiple children, and sub-children

Here my code:

std::map<std::string, std::string> myClassMap; // 1. String (key) = Classname, 2. String = BaseClass


myClassMap.insert ( std::pair<std::string, std::string>("DerivedClass1", "OverallBaseClass"));
myClassMap.insert ( std::pair<std::string, std::string>("DerivedClass2", "OverallBaseClass"));
myClassMap.insert ( std::pair<std::string, std::string>("DerivedClass3", "OverallBaseClass") );
myClassMap.insert ( std::pair<std::string, std::string>("DerivedClass2-1'","DerivedClass2") );
myClassMap.insert ( std::pair<std::string, std::string>("DerivedClass2-1-1","DerivedClass2-1") );
myClassMap.insert ( std::pair<std::string, std::string>("DerivedClass2-1-2","DerivedClass2-1") );
myClassMap.insert ( std::pair<std::string, std::string>("DerivedClass2-2","DerivedClass2") );


  //and so on

I have a method:

void addTreeChild(QTreeWidgetItem *parent, std::string keyClassName)
{

    QTreeWidgetItem *treeItem = new QTreeWidgetItem();
    treeItem->setText(0, QString(keyClassName));
    parent->addChild(treeItem);

}

which i can call and add the children to the tree. Now my question is, how can i iterate trough the map, and add the children to my tree, so it arise a Class-Hierarchy

1

There are 1 answers

2
Support Ukraine On

First of all remember that strings need double quotes - not single.

You probably want a multimap instead of a map as you are using the same key several times (which can't be done in a map).

You can iterate like this:

for (auto i : myClassMap)
{
    // i.first now holds the first string (key)
    // i.second now holds the second string (value)
}

So something like:

    std::multimap<std::string, std::string> myClassMap;
    myClassMap.insert ( std::pair<std::string, std::string>("OverallBaseClass", "DerivedClass1"));
    myClassMap.insert ( std::pair<std::string, std::string>("OverallBaseClass", "DerivedClass2"));
    myClassMap.insert ( std::pair<std::string, std::string>("DerivedClass2", "DerivedClass3") );
    for (auto i : myClassMap)
    {
        cout << i.first << "," << i.second << endl;
    }

will produce:

DerivedClass2,DerivedClass3

OverallBaseClass,DerivedClass1

OverallBaseClass,DerivedClass2