Note that there are some explanatory texts on larger screens.

plurals
  1. POHow can an element find its own index in a vector?
    primarykey
    data
    text
    <p>I'm trying to reimplement a tree data structure using <code>std::unique_ptr</code>, and the idea is that the parent node would own its children, who are stored in a vector of <code>unique_ptr</code>.</p> <p>For interface reasons, I need a method where the node destroys itself. In this case, I think the node to erase itself from the children vector in its parent.</p> <p>The following implementation 'works' (in a c++11 compiler), but it is ugly as hell and I'm sure it is a sub optimum way of dealing with this problem.</p> <pre><code>#include &lt;iostream&gt; #include &lt;memory&gt; #include &lt;vector&gt; #include &lt;algorithm&gt; struct Node { typedef std::vector&lt;std::unique_ptr&lt;Node&gt;&gt; vec_node_uptr; unsigned id; Node* parent; vec_node_uptr child_nodes; // ctor Node(unsigned id): id(id){ parent = nullptr; } void add_child(Node* new_child){ new_child -&gt; parent = this; child_nodes.push_back( std::unique_ptr&lt;Node&gt;(std::move(new_child) ) ); } int where_am_i(){ int result_ = 0; for(auto&amp; i: this -&gt; parent -&gt; child_nodes) { if (this == i.get()) { return result_; } else { result_++; } } } void suicide(){ parent -&gt; child_nodes.erase(parent -&gt; child_nodes.begin()+ where_am_i()); } }; int main() { std::unique_ptr&lt;Node&gt; root(new Node(0)); root -&gt; add_child(new Node(1)); root -&gt; add_child(new Node(2)); root -&gt; child_nodes[0] -&gt; add_child(new Node(3)); root -&gt; child_nodes[0] -&gt; add_child(new Node(4)); root -&gt; child_nodes[1] -&gt; add_child(new Node(5)); root -&gt; child_nodes[1] -&gt; add_child(new Node(6)); root -&gt; child_nodes[1] -&gt; suicide(); return 0; } </code></pre> <p>Any suggestions? Maybe using <code>std::find</code>? </p>
    singulars
    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.
    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