title: Unordered map of vectors c++
body: <p>I´m trying for several hours now to get this right. What i want to do is have a map of vectors (the vectors contain pointers to objects) stored in an unnamed namespace. Classes are then allowed to access the data in the vector via a function call.</p>
  
  <pre><code>//DataHandler.cpp
  
  #include "DataHandler.h"
  
  using std::vector;
  using std::unordered_map;
  
  namespace DataHandler
  {
    namespace
    {
      unordered_map&lt; unsigned int, vector&lt;MyClass*&gt; &gt; data_map_;
    }
  
    void receiveData(unsigned int key, vector&lt; MyClass*&gt;&amp; data_vec)
    {
      //check if key already exists:
      unordered_map&lt;unsigned int, vector&lt;MyClass*&gt; &gt;::iterator it;
  
      it = data_map_.find(key);
      if (it != data_map_.end())
      {
        data_vec = it-&gt;second;
        return;
      }
  
      //generate new key with new data
      data_map_.insert(make_pair(key, vector&lt; MyClass*&gt;()));
  
      data_map_[key].push_back(new MyClass(/*some constructor arguments*/));
      // ... push back some more instances of MyClass ...
  
      //finally:
      data_vec = data_map_[key];
      return;
    }
  }
  </code></pre>
  
  <p>In some other class I do this for getting the vector:</p>
  
  <pre><code>//SomeOtherClass.cpp
  
  #include "SomeOtherClass.h"
  #include "DataHandler.h"
  
  using std::vector;
  
  void SomeOtherClass::aMethod()
  {
    vector&lt;MyClass*&gt; first;
    vector&lt;MyClass*&gt; second;
    vector&lt;MyClass*&gt; first_again;
  
    DataHandler::receiveData(1, first); //works fine
    DataHandler::receiveData(2, second); //works fine
    DataHandler::receiveData(1, first_again); // &lt;- strange behavior or segfault here
  }
  </code></pre>
  
  <p>So everything works as expected, besides if I want to access a vector which had previously been filled with MyClass instances - then I get strange behavior or a segmentation fault. 
  Can someone explain to me why this is so and how this is done right?</p>
  
  <p>Thanks!!</p>