Home > Software engineering >  How do i "filter" output from vector<Parent*>
How do i "filter" output from vector<Parent*>

Time:11-24

Here is the problem. I have vector<D2*>, where D2 is a Parent.

I add there childs: D3 and D4.

void readFromInput(std::vector<D2*>& vec) {
        std::cout << "\nSecond class input";
        int x = 0, y = 0, z = 0;
        std::cout << "\nEnter x: ";
        std::cin >> x;
        std::cout << "Enter y: ";
        std::cin >> y;
        std::cout << "Enter z: ";
        std::cin >> z;
        vec.push_back(new D3(x, y, z));

    }


void readFromInput(std::vector<D2*>& vec) {
        std::cout << "\nSecond class input";
        int x = 0, y = 0, z = 0;
        std::cout << "\nEnter x: ";
        std::cin >> x;
        std::cout << "Enter y: ";
        std::cin >> y;
        std::cout << "Enter z: ";
        std::cin >> z;
        vec.push_back(new D4(x, y, z));

    }

And here is how i output it.

void output(std::vector<D2*>& vec) {

    for (const auto& item : vec) {
        item->display();
        std::cout << " | ";
    }

}

display() is a virtual function, btw.

So, when i use "output" i see every single element in this vector, of course.

Is there any method to ignore, for example, elements from D3 or D4?

I mean when vec.push_back(new D3(1, 1, 1)), vec.push_back(new D4(2, 2, 2))

My ouput will be 1 1 1 | 2 2 2

Can it be 1 1 1| or 2 2 2| , using the same function?

CodePudding user response:

For your particular case you can use dynamic_cast<T>(expression). See some other stack overflow answers

  1. dynamic_cast and static_cast in C
  2. When should static_cast, dynamic_cast, const_cast and reinterpret_cast be used?

You can do something like this

  void output(std::vector<D2*>& vec) {
    
        for (const auto& item : vec) {
            auto ptr = dynamic_cast<D3*>(item)
            if(ptr != nullptr){
               ptr->display();
             }else{/*Do nonthing*/}
            std::cout << " | ";
        }
    
    }

Please note that this is a bad practice!

If you want this kind of functionality you should re-think that design of your program.

  •  Tags:  
  • c
  • Related