473,503 Members | 8,959 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Sort array of struct based on the data members.

Hi,
Is it possible to sort the array of struct based on the data members.
e.g.

struct {
int a ;
float b ;
char c ;
} TEMP ;

int main() {
struct TEMP array[10] ;

/* sort () ; */
}

Based on struct members, i want to sort the array[10], with out
rewriting the sort function for each member.

Any comments ??!!

Mar 14 '07 #1
4 5215
Santosh Nayak wrote:
Hi,
Please don't multi-post on Usenet.

--
Ian Collins.
Mar 14 '07 #2

"Santosh Nayak" <sa***********@gmail.comwrote in message
news:11**********************@e65g2000hsc.googlegr oups.com...
Hi,
Is it possible to sort the array of struct based on the data members.
e.g.

struct {
int a ;
float b ;
char c ;
} TEMP ;

int main() {
struct TEMP array[10] ;

/* sort () ; */
}

Based on struct members, i want to sort the array[10], with out
rewriting the sort function for each member.

Any comments ??!!
Yes. Use the standard library features.

#include <algorithm>
#include <cstddef>
#include <iostream>
#include <ostream>
#include <string>

struct s
{
int a;
float b;
char c;
};

bool by_a(const s& lhs, const s& rhs) { return lhs.a < rhs.a; }
bool by_b(const s& lhs, const s& rhs) { return lhs.b < rhs.b; }
bool by_c(const s& lhs, const s& rhs) { return lhs.c < rhs.c; }

std::ostream& operator<<(std::ostream& os, const s& obj)
{
return os << obj.a << '\t' << obj.b << '\t' << obj.c;
}

void show(const s *arr, std::size_t elems,
const std::string& prefix = "",
std::ostream& os = std::cout)
{
os << prefix;
std::copy(arr, arr + elems, std::ostream_iterator<s>(os, "\n"));
os << '\n';
}

int main()
{
s array[] =
{
{42, 3.14, 'X'},
{25, 9.99, 'A'},
{32, 7.77, 'R'},
};

const std::size_t elems(sizeof array / sizeof *array);
show(array, elems, "Unsorted:\n");

std::sort(array, array + elems, by_a);
show(array, elems, "Sorted by member a:\n");

std::sort(array, array + elems, by_b);
show(array, elems, "Sorted by member b:\n");

std::sort(array, array + elems, by_a);
show(array, elems, "Sorted by member c:\n");

return 0;
}

Output:

Unsorted:
42 3.14 X
25 9.99 A
32 7.77 R

Sorted by member a:
25 9.99 A
32 7.77 R
42 3.14 X

Sorted by member b:
42 3.14 X
32 7.77 R
25 9.99 A

Sorted by member c:
25 9.99 A
32 7.77 R
42 3.14 X
Now that you see what the standard library can do for you,
perhaps you'll be motivated to replace that array with
a std::vector.

-Mike
Mar 14 '07 #3
Define a Strict Weak Ordering function to compare two instances of
this struct and then use "sort" to sort this array for u.

Santosh Nayak wrote:
Hi,
Is it possible to sort the array of struct based on the data members.
e.g.

struct {
int a ;
float b ;
char c ;
} TEMP ;

int main() {
struct TEMP array[10] ;

/* sort () ; */
}

Based on struct members, i want to sort the array[10], with out
rewriting the sort function for each member.

Any comments ??!!
Mar 14 '07 #4
Santosh Nayak wrote:
Hi,
Is it possible to sort the array of struct based on the data members.
e.g.

struct {
int a ;
float b ;
char c ;
} TEMP ;

int main() {
struct TEMP array[10] ;

/* sort () ; */
}

Based on struct members, i want to sort the array[10], with out
rewriting the sort function for each member.

Any comments ??!!
yes you can. given std::sort(), you can pass in a Comparison functor
that basically expresses the operator< meaning for your struct which
naturally can be based on the data members of your struct.

Here is a quick example:

#include <vector>
#include <functional>

struct myStruct
{
int foo;
};

class ComparisonOp :
public std::binary_function<bool, myStruct, myStruct>
{
public:
result_type operator()( const first_argument_type &a,
const second_argument_type &b ) const
{
return (a.foo < b.foo);
}
};

int
main()
{
std::vector<myStructm;
// fill m with elements
std::sort( m.begin(), m.end(), ComparisonOp() );
}
Mar 14 '07 #5

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

Similar topics

2
2105
by: JasBascom | last post by:
I thought it was too much to put this program in with my last message. The program compiles ok, but when I execute, I get access errors. can someone put it through their compiler please. I think...
6
4174
by: Eric Smith | last post by:
Is a structure containing an incomplete array as its last element (per paragraph 2 of section 6.7.2.1 of ISO/IEC 9899:1999 (E)) itself an incomplete type? That appears to be indicated by paragraph...
16
16364
by: Gerrit | last post by:
Hello, Is it possible to sort an array with a struct in it? example: I have a struct: public struct mp3file { public int tracknr;
5
348
by: sherifffruitfly | last post by:
Hi, I'm just learning cpp, and the exercise I'm working on is basically as follows: 1) Create a struct type with 4 members (char, char, char, int). 2) Create an array of, say 3 instances of...
8
10145
by: redefined.horizons | last post by:
I would like to have an array declaration where the size of the array is dependent on a variable. Something like this: /* Store the desired size of the array in a variable named "array_size". */...
11
3754
by: skumar434 | last post by:
Hi everybody, I am faceing problem while assigning the memory dynamically to a array of structures . Suppose I have a structure typedef struct hom_id{ int32_t nod_de; int32_t hom_id;
10
2675
by: Roman Mashak | last post by:
Hello, All! I've met the code containing this kind of structure: typedef struct cmd { unsigned int Cmd; unsigned int Code; unsigned int Data; } CMD;
2
2532
by: Santosh Nayak | last post by:
Hi, Is it possible to sort the array of struct based on the data members. e.g. struct { int a ; float b ; char c ; } TEMP ;
5
3773
by: =?Utf-8?B?QXlrdXQgRXJnaW4=?= | last post by:
Hi Willy, Thank you very much for your work. C++ code doesnot make any serialization. So at runtime C# code gives an serialization error at "msg_file_s sa = (msg_file_s) bf.Deserialize(ms);"...
0
7207
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
7294
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,...
1
7015
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
7470
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...
0
5602
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
1
5026
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...
0
4693
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
0
3183
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...
0
1523
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 ...

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.