title: How to erase all elements from a vector except for the largest in a specific range?
body: <p>Suppose I have the following vector:</p>
  
  <p>The vector is a vector of pairs, and we are comparing based on the first element.</p>
  
  <pre><code>[(1,0),(0,1),(3,2),(6,3),(2,4),(4,5),(7,6),(5,7)]
  </code></pre>
  
  <p>I want to erase all elements in a specific range except the largest.</p>
  
  <p>For example, if the range was $l = 2$ and $r = 5$, then the output:</p>
  
  <pre><code>[(1,0),(0,1),(6,3),(7,6),(5,7)]
  </code></pre>
  
  <p>Now if we do this again to the output array for $l = 1$, $r = 4$, then the output:</p>
  
  <pre><code>[(1,0),(7,6)]
  </code></pre>
  
  <p>I found <a href="https://stackoverflow.com/questions/3385229/c-erase-vector-element-by-value-rather-than-by-position">this</a> which I thought would be useful here, but I don't know how to make it work for pairs.</p>
  
  <p>Here is my attempt:</p>
  
  <pre><code>int main(int argc, char const *argv[]) {
      int N;
      cin &gt;&gt; N;
      vector&lt; pair&lt;int,int&gt; &gt; vector_of_pairs(N);
  
      for (int i = 0; i &lt; N; i++) {
          int input;
          cin &gt;&gt; input;
          vector_of_pairs[i] = make_pair(input, i);
      }
  
      int l, r;
      cin &gt;&gt; l &gt;&gt; r;
  
      int max_in_range = vector_of_pairs[l].first;
  
      for (int i = l+1; i &lt;= r; i++) {
          if (vector_of_pairs[i].first &gt; max_in_range) {
              max_in_range = vector_of_pairs[i].first;
          }
      }
  
      for (int i = l; i &lt;= r; i++) {
          if (vector_of_pairs[i].first != max_in_range) {
              vector_of_pairs.erase(vector_of_pairs.begin() + i);
          }
      }
  
      printf("[");
      for(int i = 0; i &lt; vector_of_pairs.size(); i++) {
          printf("(%d,%d)", vector_of_pairs[i].first, vector_of_pairs[i].second);
      }
      printf("]\n");
  }
  </code></pre>
  
  <p>For the following input:</p>
  
  <pre><code>8              
  1 0 5 6 2 3 7 4 
  1 3
  </code></pre>
  
  <p>This is the output:</p>
  
  <pre><code>[(1,0)(5,2)(6,3)(3,5)(7,6)(4,7)]
  </code></pre>
  
  <p>But it should be</p>
  
  <pre><code>[(1,0)(6,3)(3,5)(7,6)(4,7)]
  </code></pre>
  
  <p>Also, for certain inputs I get seg faults so how can I safe guard against that?</p>