C++ STL vector Deep erase <p>How to deep erase a vector?</p> <p>Consider the following code.</p> <pre><code>#include&lt;algorithm&gt; #include&lt;iostream&gt; #include&lt;iterator&gt; #include&lt;vector&gt; using namespace std; int main(){ vector&lt;int&gt; v {1,2,3,4,5}; for_each(begin(v),end(v),[&amp;v](int&amp; n){ static auto i = (int)0; if(n == 2){ v.erase ( begin(v) +2, end(v)); } cout &lt;&lt; n &lt;&lt; " having index " &lt;&lt; i++ &lt;&lt; endl; }); v.erase ( begin(v) +2, end(v)); cout &lt;&lt; v.size() &lt;&lt; endl &lt;&lt; v[4] &lt;&lt; endl; } </code></pre> <p>Output is</p> <pre><code>1 having index 0 2 having index 1 3 having index 2 4 having index 3 5 having index 4 2 4 </code></pre> <p>What I want is accessing v[i] for any i from 2 to 4 to be invalid and compiler to throw an error.</p> <p>In simpler words how to deep erase a vector?</p>