Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to iterate through map, modify map but restore at each iteration?
    primarykey
    data
    text
    <p>I have a <code>std::map&lt;int,int&gt;</code> lets call it <code>my_map</code></p> <p>I iterate through this map using iterators and a for loop.</p> <p>Within each iteration I want to modify many elements in this map but restore it again to its original values for next iteration of the loop.</p> <p>I thought I could create a temporary copy of the iterator <code>my_temp_map</code> , but then I wouldn't be able to use the iterator to find the element I ought to be working on.</p> <p>I then thought I could create a temporary copy, work on the origin <code>my_map</code> and at the end of each loop restore the original back to the temporary copy. However I believe this would invalidate the iterators as an assignment deletes all elements</p> <p>How does one solve this problem?</p> <p><strong>Code added</strong></p> <p>So each inner loop will modify current_partition (and there is some more absent code that will store the result of the modified current_partition), but after each inner_loop I need current_loop to be restored to its former self.</p> <pre><code>std::map&lt;int,int&gt; current_partition = bitset_to_map(centre-&gt;second-&gt;bit_partitions); int num_parts = (std::max_element(current_partition.begin(), current_partition.end(),value_comparer))-&gt;second; for (std::map&lt;int,int&gt;::iterator itr = current_partition.begin(); itr != current_partition.end(); ++itr) { for (int next_part = 0; next_part&lt;num_parts+1; ++next_part) { if (next_part != itr-&gt;second) { int current_part = itr-&gt;second; itr-&gt;second = next_part; std::vector&lt;int&gt; first_changed_part, last_changed_part; for (std::map&lt;int,int&gt;::iterator new_itr = current_partition.begin(); new_itr != current_partition.end(); ++new_itr) { if (new_itr-&gt;second == current_part) first_changed_part.push_back(new_itr-&gt;first); if (new_itr-&gt;second == next_part) last_changed_part.push_back(new_itr-&gt;first); } } } } </code></pre>
    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.
    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