What will be the output of the following C++ code? [code] #include <iostream> #include <vector> using namespace std; class

What will be the output of the following C++ code?
Code:
    #include <iostream>
    #include <vector>
    using namespace std;
    class Component
    { 
        public:
        virtual void traverse() = 0;
    };
    class Leaf: public Component
    {
        int value;
        public:
        Leaf(int val)
        {
            value = val;
        }
        void traverse()
        {
            cout << value << ' ';
        }
    };
    class Composite: public Component
    {
        vector < Component * > children;
        public:
        void add(Component *ele)
        {
            children.push_back(ele);
        }
        void traverse()
        {
            for (int i = 0; i < children.size(); i++)
                children[i]->traverse();
        }
    };
    int main()
    {
        Composite containers[4];
        for (int i = 0; i < 4; i++)
            for (int j = 0; j < 3; j++)
                containers[i].add(new Leaf(i *3+j));
            for (int k = 1; k < 4; k++)
                containers[0].add(&#038;(containers[k]));
            for (int p = 0; p < 4; p++)
            {
                containers[p].traverse();
            }
    }
A. 345
B. 678
C. 901
D.
0 1 2 3 4 5 6 7 8 9 10 11
3 4 5
6 7 8
9 10 11
 
Answer: d
Explanation: In this program, We are choosing and printing the numbers based on the certain limit and this is a composite design pattern.
Output:
Code:
$ g++ cont.cpp
$ a.out
0 1 2 3 4 5 6 7 8 9 10 11 
3 4 5 
6 7 8 
9 10 11
 

Tìm kiếm

Back
Top