C/C++ Code Bites
When one has several vectors, and need to sort them simultaneously by one of them, one can contract a vector with the indices of the sorted entries.
#include <iostream>
#include <vector>
#include <utility>
using namespace std;
bool pairsort( const pair<float, int>& i, const pair<float, int>& j ) {
if( i.first < j.first ) return false;
if( j.first < i.first ) return true;
return j.second < i.second;
}
vector<int> sortmap(vector<float> org){
vector< pair<float, int> > p;
//create a pair <value, index>
for(unsigned int i= 0; i!= org.size(); i++) {
pair<float, int> a ( org.at(i), i);
p.push_back( a );
}
sort(p.begin(), p.end(), pairsort);
vector< int > ind;
//create a pair <value, index>
for(unsigned int i= 0; i!= p.size(); i++) {
ind.push_back( p.at(i).second );
}
return ind;
}
int main(){
vector<float> Jet_pt;
vector<float> Jet_eta;
vector<float> Jet_phi;
// Fill vectors...
vector<int> m = sortmap(Jet_eta);
cout << "Jets ordered by eta" << endl;
for(int i = 0; i!= m.size(); i++)
cout << i << " pt="<< Jets_pt.at(m.at(i))<< "eta="<< Jets_eta.at(m.at(i)) << endl;
return 0;
}