Note that there are some explanatory texts on larger screens.

plurals
  1. POIterating multiple lists consecutively (C++)
    primarykey
    data
    text
    <p>I have 3 classes, 2 inheriting from the other like so:</p> <pre><code>class A { public: virtual void foo() {cout &lt;&lt; "I am A!" &lt;&lt; endl;} }; class B : public A { public: void foo() {cout &lt;&lt; "B pretending to be A." &lt;&lt; endl} void onlyBFoo() {cout &lt;&lt; "I am B!" &lt;&lt; endl} }; class C : public A { public: void foo() {cout &lt;&lt; "C pretending to be A." &lt;&lt; endl} void onlyCFoo() {cout &lt;&lt; "I am C!" &lt;&lt; endl} }; </code></pre> <p>What I want to do is something like this:</p> <pre><code>list&lt;A*&gt; list_of_A; list&lt;B*&gt; list_of_B; list&lt;C*&gt; list_of_C; //put three of each class in their respective list cout &lt;&lt; "First loop:" &lt;&lt; endl; for (list&lt;B&gt;::iterator it = list_of_B.begin(); it != list_of_B.end(); ++it) { (*it)-&gt;onlyBFoo(); } cout &lt;&lt; "Second loop:" &lt;&lt; endl; for (list&lt;C&gt;::iterator it = list_of_C.begin(); it != list_of_C.end(); ++it) { (*it)-&gt;onlyCFoo(); } //This part I am not sure about cout &lt;&lt; "Third loop:" &lt;&lt; endl; for (Iterate all 3 loops i.e. *it points to As, then Bs then Cs) { (*it)-&gt;foo(); } </code></pre> <p>To output:</p> <pre><code>First loop: I am B! I am B! I am B! Second loop: I am C! I am C! I am C! Third loop: I am A! I am A! I am A! B pretending to be A. B pretending to be A. B pretending to be A. C pretending to be A. C pretending to be A. C pretending to be A. </code></pre> <p>i.e. sometimes I want to only iterate the B objects, but sometimes I want to iterate all the objects.</p> <p>One solution would be to store them all in a list, however I want to be able to loop through them in order of type i.e. the As then the Bs then the Cs.</p> <p>Another suggested solution was to use iterators or iterator_adapters, however I have never used them before and can't find a simple example to help me get started with them.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload