title: Reference as key in std::map
body: <p>Suppose some data structure:</p>
  
  <pre><code>typedef struct {
      std::string s;
      int i;
  } data;
  </code></pre>
  
  <p>If I use the field <code>data.s</code> as key when adding instances of <code>data</code> in a map of type <code>std::map&lt;std::string&amp;, data&gt;</code>, do the string gets copied? Is it safe to erase an element of the map because the reference will become invalid?</p>
  
  <p>Also do the answers to these questions also apply to an <code>unordered_map</code>?</p>
  
  <p><strong>EDIT:</strong></p>
  
  <p>This is my current solution... but adding iterator to the map is UGLY:</p>
  
  <pre><code>typedef struct {
      const std::string* s;
      int i;
  } data;
  
  std::map&lt;std::string, data&gt; map;
  typedef std::map&lt;std::string, data&gt;::iterator iterator;
  
  // add an element to the map
  iterator add_element(const std::string&amp; s) {
      std::pair&lt;iterator, bool&gt; p = states.insert(std::make_pair(s, data()));
      iterator i = p.first;
      if(p.second) {
          data&amp; d = (*i).second;
          d.s = &amp;(*i).first;
      }
      return i;
  }
  </code></pre>