473,386 Members | 1,908 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,386 software developers and data experts.

how to use sort for

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[i]].

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[i] << endl;
}

------------

Is that at all possible or am I going about it entirely the wrong way?

Jul 22 '05 #1
6 2584

"Mike" <ha*****@impkin.com> wrote in message
news:200402181253253492%haladie@impkincom...
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[i]].

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[i] << endl;
}

------------

Is that at all possible or am I going about it entirely the wrong way?


Both, its possible, and you are going about it the wrong way.

All code is untested.

To start with you need to be clear what you are sorting. In your description
you talk about a list (or maybe a vector) of ints called RANK, in your code
you use a vector of pointers called S. I'm going to assume you want a vector
of ints. Since you are sorting a vector of ints, your sort criterion has to
compare two integers. Like this

class RankCmp : public binary_function<int, int, bool>
{
public:
bool operator()(int i1, int i2) const
{
...

And you do the sort of RANK something like this

sort(RANK.begin(), RANK.end(), ...);

Now for the two bits that say ...

The RankCmp::operator() is clearly going to have to refer back to the
original object vector, so the RankCmp class needs a reference to that
vector, i.e.
class RankCmp : public binary_function<int, int, bool>
{
public:
RankCmp(const vector<OBJ>& o) : obj(o) {}
bool operator()(int i1, int i2) const
{
...
}
private:
const vector<OBJ>& obj;
};

The constructor has been added so the obj member variable can be
initialised.

Now the operator() is easy since we have a reference to the original vector,
it's just

bool operator()(int i1, int i2) const
{
return obj[i1].t < obj[i2].t;
}

And finally to fill in the last blank start the sort off with

sort(RANK.begin(), RANK.end(), RankCmp(V));

I guess you were struggling with the idea that a functor (like RankCmp) can
have member variables. It's a very powerful idea which is the great
advantage of functors over traditional function pointers.

john
Jul 22 '05 #2

"Mike" <ha*****@impkin.com> wrote
[...]

I've re-indented the code because my newsreader doesn't handle tabs
properly.
#include <algorithm>
#include <functional> // I'm assuming I need this included

class OBJ {
public:
OBJ() { t = 0.0; }
~OBJ();
float
t;
};
Apart from looking horrible (IMO), all-caps is usually only used for
preprocessor macro names, so this might confuse people. What's wrong
with "object" and "comparison_object" (or "compare_objects", or
whatever it was you intended)?
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
No, this is not OK. vector <> has no sort () member function, and
std::sort () provides an in-place sort. You either want "std::sort
(V.first (), V.last (), compOBJ ());" (after which the rank of an
object is equal to its index in V) or "std::sort (S.first (), S.last
(), compare_objects_by_pointer ());" where we have

class compare_objects_by_pointer : public std::binary_function <OBJ
* p1, OBJ * p2, bool>
{
public:
bool operator () (OBJ * p1, OBJ * p2)
{ return p1->t < p2->t; }
};

The first option (sorting V directly) is to be preferred on grounds
of simplicity and expressiveness unless there is a good reason why
not (e.g., you have found that sorting V makes the program run too
slowly, and that sorting pointers instead gives a significant
improvement).
OBJ *ob;
for (i = 0; i < 10; i++)
cout << i << "-ranked OBJ pointer is " << S[i] << endl;
}

------------

Is that at all possible or am I going about it entirely the wrong way?


It's certainly possible, but I think you should steer clear of
containers-of-pointers when possible.

Good luck,
Buster.
Jul 22 '05 #3

"John Harrison" <jo*************@hotmail.com> wrote > "Mike"
<ha*****@impkin.com> wrote in message

[...]
Now the operator() is easy since we have a reference to the original vector, it's just

bool operator()(int i1, int i2) const
{
return obj[i1].t < obj[i2].t;
}

And finally to fill in the last blank start the sort off with

sort(RANK.begin(), RANK.end(), RankCmp(V));

John, this will never work. RankCmp would be passed OBJ
objects/references/const references, not indices.
I guess you were struggling with the idea that a functor (like RankCmp) can have member variables. It's a very powerful idea which is the great advantage of functors over traditional function pointers.

john

Jul 22 '05 #4
Dear John,
Both, its possible, and you are going about it the wrong way.

Thought as much... ;-)
I think the fundamental bit was the idea of the comparison functor having a
member variable, yes.
Many thanks!

Jul 22 '05 #5

"Buster" <no***@nowhere.com> wrote in message
news:c0**********@newsg1.svr.pol.co.uk...

"John Harrison" <jo*************@hotmail.com> wrote > "Mike"
<ha*****@impkin.com> wrote in message

[...]
Now the operator() is easy since we have a reference to the

original vector,
it's just

bool operator()(int i1, int i2) const
{
return obj[i1].t < obj[i2].t;
}

And finally to fill in the last blank start the sort off with

sort(RANK.begin(), RANK.end(), RankCmp(V));


John, this will never work. RankCmp would be passed OBJ
objects/references/const references, not indices.


No, RANK is a vector of ints.

john
Jul 22 '05 #6

"John Harrison" <jo*************@hotmail.com> wrote
"Buster" <no***@nowhere.com> wrote
John, this will never work. RankCmp would be passed OBJ
objects/references/const references, not indices.


No, RANK is a vector of ints.

john


You're totally right and I apologize.
Buster.
Jul 22 '05 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
by: Thomas Philips | last post by:
I recently had the need to sort a large number of lists of lists, and wondered if an improvement to the Decorate-Sort-Undecorate idiom is in the works. Ideally, I would like to sort the list of...
1
by: Kamilche | last post by:
I've written a generic sort routine that will sort dictionaries, lists, or tuples, either by a specified key or by value. Comments welcome! import types def sort(container, key = None,...
4
by: its me | last post by:
Let's say I have a class of people... Public Class People Public Sex as String Public Age as int Public Name as string end class And I declare an array of this class...
40
by: Elijah Bailey | last post by:
I want to sort a set of records using STL's sort() function, but dont see an easy way to do it. I have a char *data; which has size mn bytes where m is size of the record and n is the...
7
by: Stuart | last post by:
The stl::sort() that comes with Dev Studio 6 is broken (it hits the degenerate case in a common situation). I have a replacement. I would like to globally do "using namespace std; except use my...
7
by: DC Gringo | last post by:
I have a datagrid that won't sort. The event handler is firing and return label text, just not the sort. Here's my Sub Page_Load and Sub DataGrid1_SortCommand: -------------------- Private...
48
by: Alex Chudnovsky | last post by:
I have come across with what appears to be a significant performance bug in ..NET 2.0 ArrayList.Sort method when compared with Array.Sort on the same data. Same data on the same CPU gets sorted a...
10
by: Woody Ling | last post by:
In 32 bits DB2 environment, is it meaningful to set sheapthres larger than 256MB for the following case.. 1. Intra-parallel is ON 2. Intra-parallel is OFF
5
by: neehakale | last post by:
I know that heap sort,quick sort and merg sort are the faster sorting algoritms than the bubble sort,selection sort,shell sort and selection sort. I got an idea,in which situation we can use...
5
by: neocortex | last post by:
Hello! I am a newbie in Python. Recently, I get stuck with the problem of sorting by two criteria. In brief, I have a two-dimensional list (for a table or a matrix). Now, I need to sort by two...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.