Home > Back-end >  Nested map with same class
Nested map with same class

Time:12-28

I would like to write a class that stores recursively the same class in a map.

I have the following source codes:

/* A.hpp */
#include <iostream>
#include <string>
#include <map>
    
class A
{
private: 
    int a;
    std::map<int, A> data;
    bool finishCycle;

public:        
    A(const int& input ) : a(input), finishCycle(false)
    { 
        func1();
    }

    void func1();
};

/* A.cpp */
void A::func1()
{
    A tmp(*this);
       
    while(!finishCycle)
    {
         a--;
    
         if (a == 0)
             finishCycle=true;
         else
             func1();
    }
    data.emplace(tmp.a, tmp);
}
/* main.cpp*/
#include "A.hpp"

int main(int argCount, char *args[])
{
    A myObj1 (3);
    std::cout << "tst" << std::endl;
    return 0;
}

This is putting all the entries in the main map. I would like to have it in a nested sequence:

  • first entry: <1, A>
  • inside first entry: <2,A>
  • inside inside first entry <3,A>

How can I change the script to do this? The nested loops still make me confused.

CodePudding user response:

Maybe this is what you want?

#include <iostream>
#include <map>

class A
{
private:
    std::map<int, A> data;
public:

    A(int n, int i = 0) { 
        if (n == i) {
            return;
        }
        data.emplace( i 1, A(n, i   1) );
    }

    void test() {
        if (!data.empty()) {
            std::cout << data.begin()->first << "\n";
            data.begin()->second.test();
        }
    }
};


int main()
{
    A a(4);
    a.test();
}

CodePudding user response:

I came up with:

#include <iostream>
#include <map>

class A
{
    private: 
        int a;
        std::map<int, A> data;
        bool finishCycle;


    public:
    
        A(const int& input ):a(input), finishCycle(false)
        {        
            func1(*this);
        }

        void func1(A& tmp);

};


void A::func1(A& tmp)
{
   
    A tmp2(tmp);

    tmp2.a--; 

    while(!finishCycle)
    {
        if (tmp2.a == 0)
        {
            (*this).finishCycle=true;
        }
        else
        {
            func1(tmp2);          
        }      
    }  

    tmp.data.emplace(tmp2.a, tmp2);        
}



int main(int argCount, char *args[])
{

    A myObj1 (4);

    std::cout << "tst" << std::endl;

    return 0;
}
  • Related