title: Two ways to assign elements of std::vector
body: <p>As far as I am aware, one can assign elements to a <code>std::vector</code> in two ways:</p>
  
  <p><code>vec[i] = value</code></p>
  
  <p><code>vec.push_back(value)</code></p>
  
  <p>However the first method doesn't appear to have an effect on <code>vec.size()</code>, and is also overwritten by subsequent calls to <code>vec.push_back()</code>. A minimal example to demonstrate:</p>
  
  <pre><code>#include &lt;iostream&gt;
  #include &lt;vector&gt;
  
  int main()
  {
      std::vector&lt;unsigned char&gt; things;
      things.reserve(2);
  
      things[0] = 'a';
      std::cout &lt;&lt; "Size after inserting a: ";
      std::cout &lt;&lt; things.size() &lt;&lt; std::endl;
  
      things.push_back('b');
      std::cout &lt;&lt; "Size after inserting b: ";
      std::cout &lt;&lt; things.size() &lt;&lt; std::endl;
  
      std::cout &lt;&lt; "Contents: ";
      for (int i=0; i&lt;2; i++)
      {
          std::cout &lt;&lt; things[i] &lt;&lt; std::endl;
      }
  
      return 0;
  }
  </code></pre>
  
  <p>The output of this program is:</p>
  
  <pre><code>Size after inserting a: 0
  Size after inserting b: 1
  Contents: b
  </code></pre>
  
  <p>So could someone please explain:</p>
  
  <ol>
  <li><p>Why is the size 0 even after we insert <code>'a'</code>?</p></li>
  <li><p>Why does <code>things.push_back('b')</code> overwrite the <code>'a'</code>?</p></li>
  </ol>
  
  <p>Note: I am using <code>unsigned char</code> because I've adapted this code from a program I'm writing that involves manipulating this type.</p>
  
  <p>Thanks in advance.</p>