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

Sorting a list

Hi All,
I have a list which contains my class objects. My class is
having two variables. I want to sort the list based on these two
variables.

Ex :
class Foo
{
...
...
public:
int nAngle;
int nDist;
};

int main()
{
std::vector<Foo> list;
...
...
//here i want to sort the list...first based on nAngle & then
nDist...
}

PS: Though in this case my variables are int, it may be anything else.
Is there any simple & generic way to do this?

Thanks,
#SKumar#

Feb 7 '06 #1
5 1842
SKumar wrote:
Hi All,
I have a list which contains my class objects. My class is
having two variables. I want to sort the list based on these two
variables.

Ex :
class Foo
{
public:
int nAngle;
int nDist;
};
std::vector<Foo> list;


That's not a list. A std::list<Foo> would be a list, but they don't
sort well.

Anyway, you need std::sort. If you tell it how to compare two Foo's, it

can sort a vector<Foo>. It can also sort a std::deque<Foo>, because
that
also has random iterators, but not std::list.

Feb 7 '06 #2
Write a predicate compare function and use the std::vector:.sort that
invokes it.

int compare_pred(const Foo& a, const Foo& b)
{
// TODO: implement a < b here
}

// invoke like this
list.sort(compare_pred);

Feb 7 '06 #3
In article <11**********************@g47g2000cwa.googlegroups .com>,
"SKumar" <Su************@gmail.com> wrote:
Hi All,
I have a list which contains my class objects. My class is
having two variables. I want to sort the list based on these two
variables.

Ex :
class Foo
{
...
...
public:
int nAngle;
int nDist;
};

int main()
{
std::vector<Foo> list;
...
...
//here i want to sort the list...first based on nAngle & then
nDist...
}

PS: Though in this case my variables are int, it may be anything else.
Is there any simple & generic way to do this?


Yes, you have to make an op< for comparing two Foos...

bool operator<( const Foo& lhs, const Foo& rhs ) {
//if ( lhs is "smaller" than rhs ) return true;
//else return false;
}

Once you have the above, you can:

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

BTW, "list" probably isn't the best name for a vector of Foo's.

--
Magic depends on tradition and belief. It does not welcome observation,
nor does it profit by experiment. On the other hand, science is based
on experience; it is open to correction by observation and experiment.
Feb 7 '06 #4
Ooops, I goofed: returns bool, vector doesn't have *member* sort .. :)
Thanks!

Feb 7 '06 #5
SKumar wrote:
I have a list which contains my class objects. My class is
having two variables. I want to sort the list based on these two
variables.


The first thing to do when you want to sort objects is to define
a [strict partial] ordering on them. For the case of your two
variables you probably could do with a lexicographical order as
you could obtain using tuples (either from TR1 or from Boost):

return tie(obj1.nAngle, obj1.nDist) < tie(obj2.nAngle, obj2.nDist);

'tie()' is a factory function creating a tuple of references and
the expression just returns the result of comparing the two created
tuples. The same effect can be obtained using appropriate logic to
compare the involved object but I consider the above much more
readable than manual alternative.

Once you have your ordering defined, you would next have to determine
how to apply the order. There are generally two possible approaches:

1. If the ordering always applies reasonably to the involved objects,
you can make the object available by overloading suitable
operators for the corresponding class. Effectively, this means
that you define 'operator<()' for objects for your class:

bool operator< (Type const& obj1, Type const& obj2) {
// e.g. the tuple expression goes here if the operator has
// appropriate access to the member variables
}

2. If the ordering is specific to the task at hand and is not really
related to the objects in general, you would rather use a
"predicate" which is just an object that can be used with the
function call operator on the involved objects. Such a predicate
can be a simple function (in which case the object is actually
just the function pointer) or a class, e.g.:

struct MyCompare {
bool operator()(Type const& obj1, Type const& obj2) const {
// comparing the objects goes here
}
};

With this in place, you could easily sort a random access sequence
of your objects using either the default predicate which happens to
be 'std::less<Type>' and simply uses 'operator<()', i.e.

std::sort(sequence.begin(), sequence.end());

or you can use the 'std::sort()' function specifying the predicate:

std::sort(sequence.begin(), sequence.end(), MyCompare());

If you really want to sort a 'std::list<Type>', you would use the
member 'sort()' because 'std::list<Type>' does not provide random
access iterators but can still be sorted efficiently.
--
<mailto:di***********@yahoo.com> <http://www.dietmar-kuehl.de/>
<http://www.eai-systems.com> - Efficient Artificial Intelligence
Feb 8 '06 #6

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

Similar topics

20
by: Xah Lee | last post by:
Sort a List Xah Lee, 200510 In this page, we show how to sort a list in Python & Perl and also discuss some math of sort. To sort a list in Python, use the “sort” method. For example: ...
19
by: Owen T. Soroke | last post by:
Using VB.NET I have a ListView with several columns. Two columns contain integer values, while the remaining contain string values. I am confused as to how I would provide functionality to...
0
by: Brian Henry | last post by:
Here is another virtual mode example for the .NET 2.0 framework while working with the list view. Since you can not access the items collection of the list view you need to do sorting another...
4
by: FBM | last post by:
Hi, I am working on a program that simulates one of the elements of ATM. The simulation stores events which occurs every some milliseconds for a certain amount of time. Every time that an event...
20
by: martin-g | last post by:
Hi. Mostly I program in C++, and I'm not fluent in C# and .NET. In my last project I began to use LinkedList<and suddenly noticed that can't find a way to sort it. Does it mean I must implement...
1
KevinADC
by: KevinADC | last post by:
Introduction In part one we discussed the default sort function. In part two we will discuss more advanced techniques you can use to sort data. Some of the techniques might introduce unfamiliar...
3
KevinADC
by: KevinADC | last post by:
If you are entirely unfamiliar with using Perl to sort data, read the "Sorting Data with Perl - Part One and Two" articles before reading this article. Beginning Perl coders may find this article...
5
by: lemlimlee | last post by:
hello, this is the task i need to do: For this task, you are to develop a Java program that allows a user to search or sort an array of numbers using an algorithm that the user chooses. The...
4
by: slapsh0t11 | last post by:
Hello! I need help with a program that I believe I am nearly done with. However, there seems to be a few details that preclude me from success. Here is my assignment: Here is my class file...
5
by: jrod11 | last post by:
hi, I found a jquery html table sorting code i have implemented. I am trying to figure out how to edit how many colums there are, but every time i remove code that I think controls how many colums...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
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: 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
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.