title: Sort one vector according to another
body: <p>I'm basing my question off the answer to this one:</p>
  
  <p><a href="https://stackoverflow.com/questions/17554242/how-to-obtain-the-index-permutation-after-the-sorting">How to obtain the index permutation after the sorting</a></p>
  
  <p>I have two std::vectors:  </p>
  
  <pre><code>std::vector&lt;int&gt; time={5, 16, 4, 7};   
  std::vector&lt;int&gt; amplitude={10,17,8,16};
  </code></pre>
  
  <p>I want to order the vectors for increasing time, so eventually they will be:</p>
  
  <pre><code>TimeOrdered={4,5,7,16};
  AmplitudeOrdered={8,10,16,17};
  </code></pre>
  
  <p>Once finished, I want to add both ordered vectors to a CERN ROOT TTree. I looked online for solutions and found the example above, where the top answer is to use the following code:</p>
  
  <pre><code>vector&lt;int&gt; data = {5, 16, 4, 7};   
  vector&lt;int&gt; index(data.size(), 0);
  for (int i = 0 ; i != index.size() ; i++) {
      index[i] = i;
  }
  sort(index.begin(), index.end(),[&amp;](const int&amp; a, const int&amp; b) {
                  return (data[a] &lt; data[b]);
                }
    );
  for (int ii = 0 ; ii != index.size() ; ii++) {
    cout &lt;&lt; index[ii] &lt;&lt; endl;
  }
  </code></pre>
  
  <p>Which I like because it's simple, it doesn't require too many lines and it leaves me with two simple vectors, which I can then use easily for my TTree.</p>
  
  <p>I tried, therefore, to generalise it:</p>
  
  <pre><code>  void TwoVectorSort(){
  
        std::vector&lt;int&gt; data={5, 16, 4, 7};   
        std::vector&lt;int&gt; data2={10,17,8,16};
        sort(data2.begin(), data2.end(),[&amp;](const int&amp; a, const int&amp; b) {
                          return (data[a] &lt; data[b]);
                        }
          );
  
        for (int ii = 0 ; ii != data2.size() ; ii++) {
          std::cout &lt;&lt;data[ii]&lt;&lt;"\t"&lt;&lt; data2[ii]&lt;&lt;"\t"&lt;&lt; std::endl;//&lt;&lt;index[ii] 
        }
  }
  </code></pre>
  
  <p>But not only does it not work, it gives me something different each time. I'm running it as a macro with ROOT 6.18/04, using .x TwoVectorSort.cpp+.</p>
  
  <p>Can anyone tell me why it doesn't work and what the simplest solution is? I'm by no means a c++ expert so I hope the answers won't be too technical!</p>
  
  <p>Thanks in advance!</p>