473,785 Members | 2,137 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 5232
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.goo glegroups.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_it erator<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_fun ction<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<myS tructm;
// 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
2120
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 the problem lies when i declare union Allrecords h1,h2,h3. and then use them to toupper record_type. the debug when i use it can not go past the switch statement. thank you for you help
6
4206
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 22 of section 6.2.5. If so, that seems to make it difficult to allocate such structures, because sizeof() is not allowed on incomplete types (paragraph 1 of section 6.5.3.4). For instance, I've routinely done things like this: struct foo {...
16
16427
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 the struct, and populate them with data. 3) cin 1, 2, 3, or 4 from the user 4) If the user selected, say, 2, display the contents of the 2nd data
8
10169
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". */ unsigned short int array_size = 25; /*Declare an array named "numbers" using the variable initialized above. */ unsigned short int numbers;
11
3787
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
2704
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
2545
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
3798
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);" I thought that it is very hard to memory map structure array. I need both read and write memory mapped file at both side of C# and C++.
0
9647
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 usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9489
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 synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10162
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 captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10100
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8988
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7509
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 instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5396
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 the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5528
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3665
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.