#include<stdio.h>
#include<algorithm>
#include<string>
using
namespace
std;
struct
product{
char
name[16];
float
price;
};
int
array_int[5]={4,1,2,5,3};
char
array_char[5]={
'a'
,
'c'
,
'b'
,
'e'
,
'd'
};
double
array_double[5]={1.2,2.3,5.2,4.6,3.5};
//结构比较函数(按照结构中的浮点数值进行排序)
bool
compare_struct_float(
const
product &a,
const
product &b){
return
a.price<b.price;
}
//结构比较函数(按照结构中的字符串进行排序)
bool
compare_struct_str(
const
product &a,
const
product &b){
return
string(a.name)<string(b.name);
}
//打印函数
void
print_int(
const
int
* a,
int
length){
printf
(
"升序排序后的int数组:\n"
);
for
(
int
i=0; i<length-1; i++)
printf
(
"%d "
,a[i]);
printf
(
"%d\n"
,a[length-1]);
}
void
print_char(
const
char
* a,
int
length){
printf
(
"升序排序后的char数组:\n"
);
for
(
int
i=0; i<length-1; i++)
printf
(
"%c "
,a[i]);
printf
(
"%c\n"
,a[length-1]);
}
void
print_double(
const
double
* a,
int
length){
printf
(
"升序排序后的dobule数组:\n"
);
for
(
int
i=0; i<length-1; i++)
printf
(
"%.2f "
,a[i]);
printf
(
"%.2f\n"
,a[length-1]);
}
void
print_struct_array(
struct
product *array,
int
length)
{
for
(
int
i=0; i<length; i++)
printf
(
"[ name: %s \t price: $%.2f ]\n"
, array[i].name, array[i].price);
puts
(
"--"
);
}
void
main()
{
struct
product structs[] = {{
"mp3 player"
, 299.0f}, {
"plasma tv"
, 2200.0f},
{
"notebook"
, 1300.0f}, {
"smartphone"
, 499.99f},
{
"dvd player"
, 150.0f}, {
"matches"
, 0.2f }};
//整数排序
sort(array_int,array_int+5);
print_int(array_int,5);
//字符排序
sort(array_char,array_char+5);
print_char(array_char,5);
//浮点排序
sort(array_double,array_double+5);
print_double(array_double,5);
//结构中浮点排序
int
len =
sizeof
(structs)/
sizeof
(
struct
product);
sort(structs,structs+len,compare_struct_float);
printf
(
"按结构中float升序排序后的struct数组:\n"
);
print_struct_array(structs, len);
//结构中字符串排序
sort(structs,structs+len,compare_struct_str);
printf
(
"按结构中字符串升序排序后的struct数组:\n"
);
print_struct_array(structs, len);
}