title: Can I avoid copying an unordered_map in C++ in the following situation?
body: <h2>Context</h2>
  
  <p>I am trying to solve the Travelling Salesman Problem using a Dynamic Programming algorithm with C++. I am trying to solve the problem for 25 cities, meaning that I have to store up to <strong>5 million key-value pairs</strong> in a <code>unordered_map</code> <strong>per iteration</strong>.  </p>
  
  <p>Using this algorithm with Python and 4GB ram I had my process killed due to lack of memory, so I'm trying to improve the performance in memory.</p>
  
  <h2>Problem</h2>
  
  <p>To reduce the amount of memory used, I am trying to keep two <code>unordered_set</code>, one with the values of the previous iteration, and another one with the new values.</p>
  
  <pre><code>std::unordered_map&lt;std::string, int&gt; costs;
  std::unordered_map&lt;std::string, int&gt; new_costs;
  
  for (int m = 1; m &lt;= n; m++) {
    new_costs.clear();
    while (something) {
      // I build the content of new_costs based on the content of costs
    }
  
    // Here I want to make costs point to new_costs and free new_costs to
    // build the next iteration
    costs = new_costs; // ??
  }
  </code></pre>
  
  <p>I don't know if I can avoid copying all <code>new_costs</code> to <code>costs</code> as we are talking about <strong>millions</strong> of elements.</p>
  
  <p>I was wondering if I could use pointers to make <code>costs</code> point to <code>new_costs</code>, but in that case I don't know what would happen when I do <code>new_costs.clear();</code>.</p>
  
  <h2>Question</h2>
  
  <p>Summing up my question is, how can I allocate new memory for <code>new_costs</code>, put the content of <code>new_costs</code> inside <code>costs</code> (hopefully in constant time?), and free the memory already used by the old <code>costs</code> that I will not use again?</p>
  
  <p>Any help is really appreciated! Thanks!</p>
  
  <p>-- Feel free to edit the title to make it more descriptive. I couldn't find a good title.</p>