MFC的CArray排序小结(结合std::sort)

MFC的CArray非常好用(相对于C/C++的静态数组),但无法根据某个成员排序。下面是结合std::sort一块实现的CArray排序,废话少说,直接上程序干货:

#include "stdafx.h"
#include "Test.h"
#include <algorithm>


#ifdef _DEBUG
#define new DEBUG_NEW
#endif

//
//	自定义的数据结构
//
typedef struct
{
	int		x;
	char	str[100];
	double	f;
}MY_T;

// 唯一的应用程序对象

CWinApp theApp;

using namespace std;

CArray <MY_T, MY_T&> myArray;

unsigned RandUInt32(unsigned int min, unsigned int max) 
{ 
	unsigned u; 
	rand_s(&u); 
	return (unsigned)((double)u / ((__int64)UINT_MAX + 1) * (max - min) + min); 
} 

//
//	下面是比较函数,三种类型
//
bool Comp_f (MY_T &p1, MY_T &p2)
{
	return p1.f > p2.f;
}

//字符串比较
bool Comp_str(MY_T &p1, MY_T &p2)
{
	if(strcmp(p1.str, p2.str) >0)
		return true;
	else return false;
}

//整数比较
bool Comp_i (MY_T &p1, MY_T &p2)
{
	return p1.x > p2.x;
}


void Print()
{
	printf("整数\t字串\t浮点数\r\n");

	for (int i=0; i<myArray.GetSize(); i++)
	{
		printf("%d\t%s\t%.3f\r\n", myArray[i].x, myArray[i].str, myArray[i].f);
	}

	printf("\r\n");
}

int _tmain(int argc, TCHAR* argv[], TCHAR* envp[])
{
	int nRetCode = 0;

	// 初始化 MFC 并在失败时显示错误
	if (!AfxWinInit(::GetModuleHandle(NULL), NULL, ::GetCommandLine(), 0))
	{
		// TODO: 更改错误代码以符合您的需要
		_tprintf(_T("错误: MFC 初始化失败\n"));
		nRetCode = 1;
	}
	else
	{
		//
		// 产生几个内容,
		//
		for (int i=0; i<5; i++)
		{
			MY_T a = {0};
			a.x = i+1;
			int x = RandUInt32(1020, 9999);
			itoa(x, a.str, 10);					//随机的4位字符串
			a.f =  x*RandUInt32(10, 99)*0.145;	//随机的浮点数

			myArray.Add(a);
		}

		//输出查看结果
		Print();

		//排序,替换最后一个函数指针参数
		std::sort(myArray.GetData(), myArray.GetData()+myArray.GetSize(), Comp_f);

		//再次输出查看结果
		Print();

	}

	return nRetCode;
}


上述程序用到了rand_s,需要将宏定义放在stdafx.h的最上面:#define _CRT_RAND_S。

还有一点需要注意:比较函数返回的是bool类型,不是整数类型(0或1),因此在比较字符串(即使用strcmp)时,要返回true或false类型!!


  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值