473,385 Members | 1,536 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,385 software developers and data experts.

Sorting a list of objects.

User-Agent: OSXnews 2.081
Xref: number1.nntp.dca.giganews.com comp.lang.c++:824790
Hi,
I have a list of objects (instantiations of class A) in a class B:

class B{
//other stuff;
list<Amylist;

}

Now I would like to sort the elements of mylist according to some
criteria. My question is how can I do it? I know stl list provides built in
sort function: where do I need to write/define this function so that I can
call something like:
mylist.sort(); ?

The class A is a concrete class. Do I need to define something the
function in class A?
thanks,
--a.


--
Oct 9 '06 #1
4 2999
Amit Bhatia wrote:
Hi,
I have a list of objects (instantiations of class A) in a class B:

class B{
//other stuff;
list<Amylist;

}

Now I would like to sort the elements of mylist according to some
criteria. My question is how can I do it? I know stl list provides built in
sort function: where do I need to write/define this function so that I can
call something like:
mylist.sort(); ?

The class A is a concrete class. Do I need to define something the
function in class A?
thanks,

You could define "<" for class A. Something like:

//within class A's definition
bool operator < (const A& rhs)
{
return (a < rhs.a);
}

Or you could define it as a free function (friendly or unfriendly :-) )
comparing two As. Something like:

bool operator < (const A& lhs, const A& rhs)
{
return (lhs.a < rhs.a);
}

In case it is a friend function you will need to add something like this
to the class definition:
friend bool operator < (const A& lhs, const A& rhs);
Regards,
Sumit.
Oct 9 '06 #2
Amit Bhatia wrote:
>
Hi,
I have a list of objects (instantiations of class A) in a class B:

class B{
//other stuff;
list<Amylist;

}

Now I would like to sort the elements of mylist according to some
criteria. My question is how can I do it? I know stl list provides built
in sort function: where do I need to write/define this function so that I
can call something like:
mylist.sort(); ?

The class A is a concrete class. Do I need to define something the
function in class A?
thanks,
You have several options:

a) define a member function

class A {
...
bool operator< ( A const & rhs ) const {
}

}

b) define a free-standing (friend) operator:

bool operator< ( A const & lhs, A const & rhs ) {
}

c) add a specialization to std::less<>:

namespace std {

template <>
struct less< A : binary_predicate< A {

bool operator() ( A const & lhs, A const & rhs ) {
}

};

d) define a free standing (friend) predicate

bool is_less ( A const & lhs, A const & rhs ) {
}

and pass this as a parameter:

mylist.sort( is_less );
The third and fourth alternatives convey the understanding that the ordering
is not natural, whereas the first two options indicate that objects of class
A allow for a canonical comparison.

The third option is often more convenient than the fourth since std::less
will be automatically used by sort() and its friends. The fourth
alternative is more appealing if you are using more than one sort order in
your program.

Best

Kai-Uwe Bux
Oct 9 '06 #3
"Kai-Uwe Bux" <jk********@gmx.netwrote in message
news:eg**********@murdoch.acc.Virginia.EDU...
: Amit Bhatia wrote:
....
: class B{
: //other stuff;
: list<Amylist;
....
: Now I would like to sort the elements of mylist according to some
: criteria. My question is how can I do it? I know stl list provides
built
: in sort function:
Just a note to the OP, as others implicitly pointed out:
an std::list can only be sorted using its member function
'sort', unlike random access containers (like std::vector
or std::queue) on which you use std::sort found in <algorithm>.

: where do I need to write/define this function so that I
: can call something like:
: mylist.sort(); ?
: >
: The class A is a concrete class. Do I need to define something the
: function in class A?
: thanks,
:
: You have several options:
:
: a) define a member function
:
: class A {
: ...
: bool operator< ( A const & rhs ) const {
: }
:
: }
:
: b) define a free-standing (friend) operator:
:
: bool operator< ( A const & lhs, A const & rhs ) {
: }
Of these two options, I always use b).
Reasons for this? :
- writing the implementation of b) is clearer,
more symmetric, and less error prone.
- implicit conversions: when using a), implicit
convertions to A will only be performed on the
rhs, but not on the lhs. Think of having a
BigInt class having a non-explicit constructor
from 'int', with a) you would not be able to
compile: bool b = 5 < myBigIntValue.

b) can directly be implemented within the class
body as follows:
friend bool operator<( A const& a, A const& b )
{ return a.m < b.m; }
: c) add a specialization to std::less<>:
:
: namespace std {
:
: template <>
: struct less< A : binary_predicate< A {
:
: bool operator() ( A const & lhs, A const & rhs ) {
: }
:
: };
I have trouble envisioning why one would want to write
this. IMO std::less still implies a natural, default
ordering of the operands, and if this is the case,
I'd rather provide the comparison operator <.
This is delicate to get right, and as far as I know,
there is no "binary_predicate" template in the standard
(you'd have to use binary_function<A,A,bool>).

: d) define a free standing (friend) predicate
:
: bool is_less ( A const & lhs, A const & rhs ) {
: }
:
: and pass this as a parameter:
:
: mylist.sort( is_less );

An alternative to this d) is to provide a predicate object:
struct AByName {
bool operator()( A const& a, A const& b )
{ return a.name < b.name; }
};
Passing it as:
mylist.sort( AByName() );

This may be more verbose, but has advantages:
- parameters can be provided to the comparison object
(and stored as data members), for example to indicate
which data member is to be used.
- I'm not sure this remains the case, but compilers used
to be more apt at inlining a predicate object than
a function provided by pointer ( = faster performance ).
So personally, I would only consider one of these 2 (or 3)
options:
- if there is a natural ordering, define operator < (as per b) )
- if there is none, use a predicate function or object
( d) or my last suggestion above )
Kind regards,
Ivan
--
http://ivan.vecerina.com/contact/?subject=NG_POST <- email contact form

Oct 9 '06 #4
Ivan Vecerina wrote:
"Kai-Uwe Bux" <jk********@gmx.netwrote in message
[snip]
: c) add a specialization to std::less<>:
:
: namespace std {
:
: template <>
: struct less< A : binary_predicate< A {
:
: bool operator() ( A const & lhs, A const & rhs ) {
: }
:
: };
I have trouble envisioning why one would want to write
this. IMO std::less still implies a natural, default
ordering of the operands, and if this is the case,
I'd rather provide the comparison operator <.
I feel a difference between a default total order (such as the one used by
set<>) and a natural ordering. This may depend on the local culture as it
is a matter or conveying intent and not in any way legislated by the
standard.

I overload std::less routinely for types for which there is a total ordering
that can be computed efficiently. The reason is simple: I want to be able
to use std::set<and std::map<without further thought; and in the
absence of a natural order, I want them to use an efficient method by
default. I only make operator< available if there is a natural meaning. For
instance, I would provide a specialization of std::less for a
free_group_element<Rankclass (and I would make it fast) but I would not
provide operator<.

However, I can see that there are reasons to think of std::less<Tas still
pretending to be natural: after all it is the default used in std::sort.

This is delicate to get right, and as far as I know,
there is no "binary_predicate" template in the standard
(you'd have to use binary_function<A,A,bool>).
Right about the binary_predicate, which should be in std but isn't :-(
However, I do not really see what is so hard about getting a partial
specialization for std::less<right. It is not any more difficult than
implementing a comparison function object of your own choice.

: d) define a free standing (friend) predicate
:
: bool is_less ( A const & lhs, A const & rhs ) {
: }
:
: and pass this as a parameter:
:
: mylist.sort( is_less );

An alternative to this d) is to provide a predicate object:
struct AByName {
bool operator()( A const& a, A const& b )
{ return a.name < b.name; }
};
Passing it as:
mylist.sort( AByName() );

This may be more verbose, but has advantages:
- parameters can be provided to the comparison object
(and stored as data members), for example to indicate
which data member is to be used.
- I'm not sure this remains the case, but compilers used
to be more apt at inlining a predicate object than
a function provided by pointer ( = faster performance ).
[snip]

Right, I missed that option.
Thanks

Kai-Uwe Bux

Oct 9 '06 #5

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

Similar topics

6
by: praba kar | last post by:
Dear All, I have doubt regarding sorting. I have a list that list have another list (eg) list = ,,] I want to sort only numeric value having array field. How I need to do for that.
18
by: Matthias Kaeppler | last post by:
Hi, in my program, I have to sort containers of objects which can be 2000 items big in some cases. Since STL containers are based around copying and since I need to sort these containers quite...
1
by: aredo3604gif | last post by:
On Sun, 10 Apr 2005 19:46:32 GMT, aredo3604gif@yahoo.com wrote: >The user can dynamically enter and change the rule connection between >objects. The rule is a "<" and so given two objects: >a <...
25
by: Dan Stromberg | last post by:
Hi folks. Python appears to have a good sort method, but when sorting array elements that are very large, and hence have very expensive compares, is there some sort of already-available sort...
9
by: Daz | last post by:
Hello people! (This post is best viewed using a monospace font). I need to create a class, which holds 4 elements: std::string ItemName int Calories int Weight int Density
16
by: Kittyhawk | last post by:
I would like to sort an Arraylist of objects on multiple properties. For instance, I have a Sort Index property and an ID property (both integers). So, the results of my sort would look like this:...
4
by: semedao | last post by:
Hi, I want to implement list of key-values that can be sort by 2 ways. let's say that in the first step I wanted to make SortList based on Key = int index that cannot change and Value is another...
3
by: Harry Haller | last post by:
Hello, I want to implement a generic list which will be used to display 7 columns in a GridView. One should be able to sort, filter and page each of the 7 columns. Ideally the filter should be...
2
by: Jason | last post by:
Hi folks-- Basically, I have a pressing need for a combination of 5.2 "Sorting a List of Strings Case-Insensitively" & 5.3 "Sorting a List of Objects by an Attribute of the Objects" from the...
3
by: =?Utf-8?B?U2NvdHQ=?= | last post by:
Good afternoon, I would like to mimic the sorting capabilities in Excel where I can sort a list by up to four properties (columns in excel). I would like to pass a collection of objects to a...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 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 former...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
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...

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.