M
Mike
Hi there,
I'm very new to the STL and am struggling a bit with a sort, and would love
some help if possible!
I have a simple array V of objects of class OBJ that I want to rank in
order of the float OBJ.t and put the ranks into a list of ints, call it
RANK, so I can then access the OBJ with the i-th smallest value of t by
V[RANK].
This is hideous and does not take advantage of STL's sort algorithm.
I want to use a sort(random_access_iterator first, random_access_iterator
last, compare comp) for this but I don't know how.
I'd like to sent up with something *like*
#include <algorithm>
#include <functional> // I'm assuming I need this included
class OBJ {
public:
OBJ() { t = 0.0; }
~OBJ();
float
t;
};
class compOBJ : public binary_function<OBJ &o1, OBJ &o2, bool>
{
public:
bool operator()(OBJ &o1, OBJ &o2)
{ return (o1.t < o2.t); }
};
int main()
{
vector<OBJ>
V(10);
vector<OBJ*>
S(10); // vector of pointers to OBJ
int i;
for (i = 0; i < 10; i++)
V.t = (float) rand(); // put in some random vals
S.sort(V.first, V.last, compObj); // sort the objects in V and put their
pointers in order into S
OBJ *ob;
for (i = 0; i < 10; i++)
cout << i << "-ranked OBJ pointer is " << S << endl;
}
I'm very new to the STL and am struggling a bit with a sort, and would love
some help if possible!
I have a simple array V of objects of class OBJ that I want to rank in
order of the float OBJ.t and put the ranks into a list of ints, call it
RANK, so I can then access the OBJ with the i-th smallest value of t by
V[RANK].
This is hideous and does not take advantage of STL's sort algorithm.
I want to use a sort(random_access_iterator first, random_access_iterator
last, compare comp) for this but I don't know how.
I'd like to sent up with something *like*
#include <algorithm>
#include <functional> // I'm assuming I need this included
class OBJ {
public:
OBJ() { t = 0.0; }
~OBJ();
float
t;
};
class compOBJ : public binary_function<OBJ &o1, OBJ &o2, bool>
{
public:
bool operator()(OBJ &o1, OBJ &o2)
{ return (o1.t < o2.t); }
};
int main()
{
vector<OBJ>
V(10);
vector<OBJ*>
S(10); // vector of pointers to OBJ
int i;
for (i = 0; i < 10; i++)
V.t = (float) rand(); // put in some random vals
S.sort(V.first, V.last, compObj); // sort the objects in V and put their
pointers in order into S
OBJ *ob;
for (i = 0; i < 10; i++)
cout << i << "-ranked OBJ pointer is " << S << endl;
}