"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