473,586 Members | 2,707 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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_acc ess_iterator first, random_access_i terator
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 2600

"Mike" <ha*****@impkin .com> wrote in message
news:2004021812 53253492%haladi e@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_acc ess_iterator first, random_access_i terator
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::operat or() 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_obj ect" (or "compare_object s", 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_fun ction <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.p ol.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
2005
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 lists (or tuples) in place by using a simple variant of the current idiom, i.e. list_of_lists.sort(*columns) where *columns is a tuple that...
1
2277
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, ascending = True): ' Sort lists or dictionaries by the specified key' t = type(container)
4
3735
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
4245
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 number of records. Both these numbers are known
7
2442
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 sort()". I'd heard you can do this within a namespace: namespace Fixed { using namespace std;
7
2439
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 Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load 'Put user code to initialize the page here
48
4439
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 lot faster with both methods using .NET 1.1, that's why I am pretty sure its a (rather serious) bug. Below you can find C# test case that should...
10
5587
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
16623
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 bubble sort(use when we have to 100 items: bubble sort is effective),shell sort is effective when one has to sort near abt 5000 items..selection sort is...
5
7803
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 columns, but I cannot figure out how to do that. I read somewhere that it is possible to do: but it does not work. Can anyone help me with this? PS:...
0
7912
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7839
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
8338
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
0
8216
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
1
5710
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
3837
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
0
3865
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2345
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1449
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.