Skip to main content
GameDev.net gamedev.net
🔒 Locked

Sort STL Vector which contain struct

Started by JoeZ Jul 20, 2002 at 2:21 PM 2 replies 3k views
Original Post
JoeZ
JoeZ
Hi: I pushed 10 point3D struct into a vector. is there a function in STL to sort the vector according to the z value in the point3D struct? OR DO I have to implement the sort myself Thank you.
Vetinari
Vetinari
std::sort allows you to pass a callback to sort however you want.


Mike
"Unintentional death of one civilian by the US is a tragedy; intentional slaughter of a million by Saddam - a statistic." - Unknown
FrigidHelix
FrigidHelix
Yeah. Use the std::sort function (defined in ), and pass a predicate object. For example, u might define these classes:

  
// Function object to sort by ascending Z order

struct SortByZValAsc
{
bool operator()(const point3D& p1, const point3D& p2)
{ return p1.z < p2.z;}
};

// Function object to sort by descending Z order

struct SortByZValDesc
{
bool operator()(const point3D& p1, const point3D& p2)
{ return p2.z < p1.z; }
};

The to sort your vector v you would jsut do:

  
sort(v.begin(), v.end(), SortByZValAsc());
// or

sort(v.begin(), v.end(), SortByZValDesc());

Here is full source for an example:

  
#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

// Your point structure

struct point3D
{
float x,y,z;
point3D(float ix, float iy, float iz) : x(ix), y(iy), z(iz) {}
};

// Function object to sort by ascending Z order

struct SortByZValAsc
{
bool operator()(const point3D& p1, const point3D& p2)
{ return p1.z < p2.z;}
};

// Function object to sort by descending Z order

struct SortByZValDesc
{
bool operator()(const point3D& p1, const point3D& p2)
{ return p2.z < p1.z; }
};

int main()
{
// Fill in a vector with points (in random Z order)

vector<point3D> v;
v.push_back(point3D(3.0f,0.0f,1.3f));
v.push_back(point3D(-5.0f,0.0f,0.3f));
v.push_back(point3D(3.0f,2.0f,6.3f));
v.push_back(point3D(1.0f,0.0f,7.3f));

// Sort list by ascending

sort(v.begin(), v.end(), less<point3D> ());

// Print the list in its new order

cout << "List in ascending Z order" << endl;
vector<point3D>::iterator it = v.begin();
for(;it!=v.end(); it++)
cout << it->x << ", " << it->y << ", " << it->z << endl;

// Sort list by descending

sort(v.begin(), v.end(), SortByZValDesc());

// Print the list in its new order

cout << "\nList in ascending Z order" << endl;
it = v.begin();
for(;it!=v.end(); it++)
cout << it->x << ", " << it->y << ", " << it->z << endl;

return 0;
}

Also, you could define the operator< and/or operator> for point3D, then use the less binary predicate object.
JoeZ
JoeZ
Wow! Thank you guys

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.