title: C++ STL vector iterator vs indexes access and thread safety
body: <p>I am iterating over an STL vector and reading values from it. There is another thread which can make changes to this vector. Now, if the other thread inserts or removes and element from the vector, it invalidates the iterator. There is no use of locks involved.  Does my choice of accessing the container through indexes(Approach 1) in place of iterators(Approach 2) make it thread safe? What about performance?</p>
  
  <pre><code>struct A{int i; int j;};
  </code></pre>
  
  <p>Approach 1:</p>
  
  <pre><code>   size_t s = v.size();//v contains pointers to objects of type A
      for(size_t i = 0; i &lt; s; ++i)
      {
           A* ptr = v[i];
           ptr-&gt;i++;
      }
  </code></pre>
  
  <p>Approach 2:</p>
  
  <pre><code>std::vector&lt;A*&gt;::iterator begin =  v.begin();
  std::vector&lt;A*&gt;::iterator end =  v.end();
  for(std::vector&lt;A*&gt;::iterator it = begin; it != end; ++it)
  {
       A* ptr = *it;
       ptr-&gt;i++: 
  }
  </code></pre>