Hi,
I am trying to sort a vector of a user defined type: a class which represents points in cartesian coordinates. The vector of points needs to be sorted according to the value of the x-coordinate. I am trying to use the "sort" function defined in algorithms.h and I am getting a segmentation fault. I have inlined the code below. Can someone please tell me what I am doing wrong ? I am compiling this code on linux ( fedora 6 x86_64 using gcc 4.0)
-
Many thanks
JWalker
PS: I am just learning C++ and STL perhaps I am making some fundamental mistake.
================================================== =====
#include <iostream>
#include <fstream>
#include <iterator>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
class _vertex{
public:
double x;
double y;
double z;
_vertex() {x=0.0, y =0.0; z =0.0;}
_vertex(double xa,double ya, double za){x=xa; y =ya; z=za;}
_vertex (const _vertex & b) {x = b.x; y=b.y; z=b.z;}
};
bool sortbyx(const _vertex& v1,const _vertex& v2){
if(v1.x<=v2.x)
return true;
else
return false;
}
void print(const _vertex& tmp){
cout<<tmp.x<<"\t"<<tmp.y<<"\t"<<tmp.z<<"\t"<<endl;
}
int main(){
vector<_vertex> nodes;
// read node information from files in vector "qvolist"
vector<string> qvolist;
qvolist =Read_qvofile_list("temp.txt");
for(int i =0; i<qvolist.size();i++){
ifstream qvofile;
string line;
int Nvertices, NFaces, NEdges;
qvofile.open((qvolist.at(i)).c_str());
cout<<(qvolist.at(i))<<endl;
if(qvofile.is_open())
{
getline(qvofile,line); // read dimensions dummy var
qvofile>>Nvertices>>NFaces>>NEdges;
_vertex tmp;
for(int j =0; j<Nvertices; j++){
qvofile>>tmp.x>>tmp.y>>tmp.z;
nodes.push_back(tmp);
}
qvofile.close();
}
else cout<<"unable to open qvo file"<<(qvolist.at(i)).c_str()<<endl;
}
// print list of vertices
for_each(nodes.begin(), nodes.end(),print);
//Sort vertices by x co-ordinate
sort(nodes.begin(), nodes.end(),sortbyx);<-----------segmentation fault here
================================================== ========