I have a set of points (x,y,z). I want to sort these data using first column and 2nd and 3rd columns should be rearranged according to the sorting 1st column. is it possible to do this in c++, if so could you pls help me.
Herewith I am attaching codes of my implementation but I got a error message “invalid conversion from ‘const’ vod*’ to ‘const int [*][3]’ “ in line 31 and 32. I tried this using several methods but my effort was not success yet. I used here ‘qsort’ for this, are there any other methods or can I use ‘sort’ in to do this. Since I have a very big data set I wish to use a fast method.
So what I need at the end the data set which is sorted using only 1st column like following example:
before sort
34 12 12
12 34 15
24 20 34
13 11 10
40 23 32
after sort
12 34 15
13 11 10
24 20 34
34 12 12
40 23 32
if any good methods help me to write codes …thanks
#include <iostream>
#include <cstdlib>
#include <vector>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
class Point
{
private:
double x;
double y;
double z;
public:
Point(){};
~Point(){};
Point(double X, double Y, double Z){
x=X;y=Y;z=Z; }
double X(){return x;}
double Y(){return y;}
double Z(){return z;}
};
int cmp ( const void *pa, const void *pb ) {
const int (*a)[3] = pa;
const int (*b)[3] = pb;
if ( (*a)[1] < (*b)[1] ) return -1;
if ( (*a)[1] > (*b)[1] ) return +1;
return 0;
}
int main ( ) {
vector<Point> points;
int input_x,input_y,input_z;
int i=0;
while(i<6){//data set,it is a example, actual data come from a file
cout<<"x: ";cin>>input_x;
cout<<"y: ";cin>>input_y;
cout<<"z: ";cin>>input_z;
Point point(input_x,input_y,input_z);
points.push_back(point);
i++;
}
for (int i=0;i<points.size();i++){//before sort
cout<<points[i].X()<<" "<<points[i].Y()<<" "<<points[i].Z()<<endl;
}
qsort( points, 6, sizeof points[0], cmp );
for (int i=0;i<points.size();i++){//after sort
cout<<points[i].X()<<" "<<points[i].Y()<<" "<<points[i].Z()<<endl;
}
system("PAUSE");
return 0;
}
It’s almost certainly easiest to use
std::sortinstead ofqsort:Edit: to keep the comparison separate from the items being compared, you use a separate function or functor to do the comparison, and pass that to
std::sort. There are a few things about your class that you really want to change in any case though — at the very least, since yourPoint::X(),Point::Y()andPoint::Z()don’t modify the Point object, you want to make themconstmember functions. Once you’ve done that, the sorting is fairly trivial:Technically, I suppose I should add one more minor detail: if the
xvalue in any of your points is a NaN, this won’t work correctly. A NaN isn’t equal to anything (not even itself) which violates the strict weak ordering required forstd::sort.