title: C++ sort on vector using function object
body: <p>I'm trying to sort a vector v1 using another vector v2. I can't wrap my head around this error:</p>
  
  <blockquote>
    <p>terminate called after throwing an instance of 'std::out_of_range'<br>
    what():  vector::_M_range_check<br>
    Abort trap</p>
  </blockquote>
  
  <p>while running this code:</p>
  
  <pre><code>#include &lt;iostream&gt;
  #include &lt;vector&gt;
  #include &lt;algorithm&gt;
  using namespace std;
  
  class Comp
  {
      public:
          Comp(vector&lt;double&gt;&amp; inVec): _V(inVec) {}
          bool operator()(int i, int j) {return (_V.at(i)&lt;_V.at(j));}
      private:
          vector&lt;double&gt; _V;
  };
  
  int main(int argc, char** argv)
  {
      double x1[] = {90.0, 100.0, 80.0};
      double x2[] = {9.0, 3.0, 1.0};
      vector&lt;double&gt; v1(x1,x1+3);
      vector&lt;double&gt; v2(x2,x2+3);
  
      sort(v1.begin(), v1.end(), Comp(v2));  // sort v1 according to v2
  
      for(unsigned int i=0; i&lt;v1.size(); i++)
      {
          cout &lt;&lt; v1.at(i) &lt;&lt; " " &lt;&lt; v2.at(i) &lt;&lt; endl;
      }
  
      return 0;
  }
  </code></pre>
  
  <p><code>v1</code> and <code>v2</code> are of the same size. Why the <code>out_of_range</code> error?</p>
  
  <p>Thanks in advance for any pointers.</p>