[prev in list] [next in list] [prev in thread] [next in thread] 

List:       suse-programming-e
Subject:    Re: [suse-programming-e] C++ sorting using STL sort()
From:       Jerry Feldman <gaf () blu ! org>
Date:       2005-06-03 12:33:10
Message-ID: 200506030833.11040.gaf () blu ! org
[Download RAW message or body]

On Friday 03 June 2005 8:16 am, Filippos Papadopoulos wrote:
> On Fri, 3 Jun 2005, Filippos Papadopoulos wrote:
> > Hi.
> >
> > In my program i am trying to sort a deque using STL sort algorithm:
> >
> >
> > deque<double> q;
> >
> > /* fill q with some doubles*/
> > ...
> > /* sort */
> > sort(q.begin(), q.end());
> >
> >
> > The above works OK.
> >
> >
> >
> > The problem is that now i want to have the following deque:
> >
> >
> > struct rrTask
> > {
> > 	double C;
> > 	int tid;
> > };
> > deque<rrTask> q;
> >
> > /* fill q with some rrTasks*/
> > rrTask rt;
> > rt.C = A_DOUBLE;
> > rt.tid = AN_INT;
> > q.push_back(rt);
> >
> > /* Try to sort q !!!*/
> > sort(q.begin(), q.end(), rt.C);
> >
> >
> > The above seems to be wrong. My intention is to sort  q using rt.C
> > field as the
> > sort key. What is the right (and easiest) way to do this?
> >
> >
> > Thanks.
>
> Replying to my email.
>
> I think i found the solution:
>
>
> I modified rrTask like this
>
> class rrTask
> {
>  	public:
>
>  		double C;
>  		int tid;
>  		bool operator() (const rrTask& x, const rrTask& y) const
>  		{
>  			return (x.C < y.C);
>  		}
>
>  		bool operator() (const rrTask& x, const double& _C) const
>  		{
>  			return (x.C < _C);
>  		}
>
> };
>
>
> And now i call sort like this:
>
> sort(qs.begin(), qs.end(), rrTask());
>
> Also i call lower_bound with rrTask() as the comperator.
I'm glad you found the solution yourself. 
Just one comment, it is probably preferable to make C and tid as private 
elements.  One of the principles of C++ is that you can hide data elements 
of a class from an implementation that uses the class, and then provide 
accessor functions to allow users of the class to access and to modify 
those elements. Since your () functions are member functions, they can 
access C directly. 
-- 
Jerry Feldman <gaf@blu.org>
Boston Linux and Unix user group
http://www.blu.org PGP key id:C5061EA9
PGP Key fingerprint:053C 73EC 3AC1 5C44 3E14 9245 FB00 3ED5 C506 1EA9

-- 
To unsubscribe, email: suse-programming-e-unsubscribe@suse.com
For additional commands, email: suse-programming-e-help@suse.com
Archives can be found at: http://lists.suse.com/archive/suse-programming-e

[prev in list] [next in list] [prev in thread] [next in thread] 

Configure | About | News | Add a list | Sponsored by KoreLogic