Note that there are some explanatory texts on larger screens.

plurals
  1. POMake a c++ iterator that traverses 2 containers
    text
    copied!<p>I have a need for a "container" that acts like the following. It has 2 subcontainers, called A and B, and I need to be able to iterate over just A, just B, and A and B combined. I don't want to use extra space for redundant data, so I thought of making my own iterator to iterate over A and B combined. What is the easiest way to make your own iterator? Or, what is another way to do this?</p> <p><strong>EDIT</strong> Ultimately, I don't think it was good design. I have redesigned the entire class heirarchy. +1 for refactoring. However, I did solve this problem sufficiently. Here's an abbreviated version of what I did, for reference; it uses boost::filter_iterator. Let T be the type in the container.</p> <pre><code>enum Flag { A_flag, B_flag }; class T_proxy { public: T_proxy(const T&amp; t, Flag f) : t_(t), flag_(f) {} operator T() const {return t_;} Flag flag() const {return flag_;} class Compare { public: Compare(Flag f) : matchFlag_(f) {} operator() (const T_proxy&amp; tp) {return tp.flag() == matchFlag_;} private: Flag matchFlag_; }; private: T t_; Flag flag_; }; class AB_list { public: typedef T_proxy::Compare Compare; typedef vector&lt;T_proxy&gt;::iterator iterator; typedef boost::filter_iterator&lt;Compare, iterator&gt; sub_iterator; void insert(const T&amp; val, Flag f) {data_.insert(T_proxy(val, f));} // other methods... // whole sequence iterator begin() {return data_.begin();} iterator end() {return data_.end();} // just A sub_iterator begin_A() {return sub_iterator(Compare(A_flag), begin(), end()); sub_iterator end_A() {return sub_iterator(Compare(A_flag), end(), end()); // just B is basically the same private: vector&lt;T_proxy&gt; data_; }; // usage AB_list mylist; mylist.insert(T(), A_flag); for (AB_list::sub_iterator it = mylist.begin_A(); it != mylist.end_A(); ++it) { T temp = *it; // T_proxy is convertible to T cout &lt;&lt; temp; } </code></pre>
 

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