Vector sort with a struct?

A

{AGUT2} {H}-IWIK

Guys, I have these headers:
#include <stdlib>
#include <math>
#include <iostream>
#include <iomanip>
#include <fstream>
#include <vector>
#include <string>
#include <algorithm>

*amongst others) and a a data structure:

// Creates part of basic framework of the output numbering system
struct vertexPoints {
int num;
double xc;
double yc;
double zc;
};

from this, I have created a vector

vector<vertexPoints> myPoints;

with vertices push_back()'ed onto it. I want to be able to sort this -
mainly by x, but ideally by x, then y, then z.

if I type mypoints.sort(myPoints.begin(), myPoints.end, comparex);

with

bool comparex(myPoints& x, myPoints& y)
{
return x.xc < y.xc;
}

the compiler throws a tantrum saying that sort is not a member function of
the vertex<myPoints> vector.

What am I doing wrong?

TIA,

Alex.
 
T

tom_usenet

Guys, I have these headers:
#include <stdlib>
#include <math>
#include <iostream>
#include <iomanip>
#include <fstream>
#include <vector>
#include <string>
#include <algorithm>

*amongst others) and a a data structure:

// Creates part of basic framework of the output numbering system
struct vertexPoints {
int num;
double xc;
double yc;
double zc;
};

from this, I have created a vector

vector<vertexPoints> myPoints;

with vertices push_back()'ed onto it. I want to be able to sort this -
mainly by x, but ideally by x, then y, then z.

if I type mypoints.sort(myPoints.begin(), myPoints.end, comparex);

std::sort(myPoints.begin(), myPoints.end, comparex);
with

bool comparex(myPoints& x, myPoints& y)

bool comparex(myPoints const& x, myPoints const& y)

{
return x.xc < y.xc;
}

the compiler throws a tantrum saying that sort is not a member function of
the vertex<myPoints> vector.

Sort is not a member of vector, it is a namespace std function.

Tom
 
P

Peter Kragh

tom_usenet said:
std::sort(myPoints.begin(), myPoints.end, comparex);

Should probably be:

std::sort(myPoints.begin(), myPoints.end(), comparex);
bool comparex(myPoints const& x, myPoints const& y)

Try:

bool comparex(const vertexPoints& x, const vertexPoints& y)

instead.
Sort is not a member of vector, it is a namespace std function.

Tom

You could also consider making a "bool operator<(const vertexPoints&)" in
your vertextPoints struct. Then you could use the sort function like this:

std::sort(myPoints.begin(), myPoints.end());

That is IMHO a more object oriented way of doing this.

BR,
Peter Kragh
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,994
Messages
2,570,223
Members
46,812
Latest member
GracielaWa

Latest Threads

Top