c++ - sort one vector in a class and the second vector should move with the first -


i want sort vector<vector<double> > , record original index vector<int>

ex a[0][1].............[n], , a[0][0] = x, a[0][1] = y, a[0][2] = z                     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 

so write following code, , want use stl sort, don't know how write compare function.

class point{     public:     point(int totallength = 0, int elementlength = 0);     vector<vector<double> > pointset;     vector<double> pointindex; }; point::point(int totallength, int elementlength){     pointset.resize(totallength,vector<double>(elementlength, 0));     pointindex.resize(elementlength); } 

and suggestion or other way achieve it?

thank reading.

the first thing i'm talking introducing separate data structure points. usually, when talk points , geometry, know exact number dimensions. so, can use

struct point { double x; double y; double z; }; 

instead of

std::vector<double> 

even if not know number of dimensions, you'd better use

typedef std::vector<double> point; 

to represent single point.

and std::vector<std::vector<double> > becomes std::vector<point>. easier read @ least.

then, impossible sort 2 arrays simultaneously, using std::sort. so, have combine pointset , pointindex array in 1 data structure sort.

an obvious way, can create

typedef std::pair<point, int> indexedpoint; std::vector<indexedpoint> indexedpoints; 

then fill structure given points , indexes , sort:

for(int indx = 0; indx < pointsset.size(); ++indx) {     indexedpoints.push_back(std::make_pair(pointsset[indx], indx)); } std::sort(indexedpoints.begin(), indexedpoints.end(), &lessthen); 

less implementation depends on algorithm of comparison. example, if want compare point first coordinate, can write

bool lessthen(const indexedpoint& l, const indexedpoint& r) {     return l.first.x < r.first.x; //or return l.first[0] < r.first[0]; -- ensure point has @ lest 1 dimension here! } 

Comments

Popular posts from this blog

Perl - how to grep a block of text from a file -

delphi - How to remove all the grips on a coolbar if I have several coolbands? -

javascript - Animating array of divs; only the final element is modified -