c++ - sort n-dimension point and keep track of original index -
i have set of n- dimension point store in vector< vector<double> >
ex a[0][1].............[n], , a[0][0] = x, a[0][1] = y, a[0][2] = z
and want sort vector of of dimension
ex sort x, y, z ,.........n in ascending order ex a[0] = (1,5,3), a[1] = (3,2,1) a[2] = (2,8,4) after sorting index: 0 1 2 a[0] = (1,5,3), a[1] = (2,8,4) a[2] = (3,2,1) original index : 0 2 1
i find sort(vector.begin(), vector.end())
can sort how can record original index additional vector?
is there algorithm or c++ feature can solve it?
thx in advance.
you need somehow keep information index. can see 2 ways of doing :
1-since represent point vector, can had dimension represent orginal index :
//adding index info, inportant index last dimension , otherwise sort incorrect for(auto point = vector.begin(),unsigned int index=0;point != vector.end(); ++point,++index){ point->push_back(index) };
then sort same way doing :
sort(vector.begin(), vector.end())
and access original index a[0][n]
the cool thing allow keep track of index in convenient way, need able modify representation of point.
2- other way have external table of indices , sort using custom comp. operator :
you start creating vector of indices
std::vector indices(vector.size());
for(unsigned int index =0;index != indicies.size(); ++point){ indicies[index] = index ; };
//and sort...
std::sort(indices.begin(),indices.end(),[&](unsigned int i,unsigned int j) { return vector[i] < vector[j]})
now need additional level of indirection go trough points in sorted order : a[indices[0]],a[indices[1]],... original position of a[indices[x]] x
the main remember between 2 ways of doing in first move data around , not in second , depending on doing on points, 1 might better order
Comments
Post a Comment