boost自定义composite_key_compare比较函数

清泛原创
// boost_demo.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"

#include "boost/shared_ptr.hpp"
#include "boost/bimap.hpp"
#include "boost/tuple/tuple.hpp"
#include "boost/multi_index_container.hpp"
#include "boost/multi_index/member.hpp"
#include "boost/multi_index/ordered_index.hpp"
#include "boost/multi_index/composite_key.hpp"
#include "boost/multi_index/identity.hpp"
#include "boost/multi_index/sequenced_index.hpp"
#include "boost/multi_index/mem_fun.hpp"

using boost::multi_index_container;
using namespace boost::multi_index;

typedef char IDType[81];

struct TParam
{
	IDType ID;
	bool IsValid;
};

typedef TParam* TParam_p;
struct TParamIDIndex { };
struct TParamValidIndex { };

struct customize_compare
{
  int operator()(const IDType l, const IDType r)const
  {
    // specially compare for this application
	  return strcmp(l, r);
  }
};

typedef multi_index_container<
	TParam_p,

	indexed_by<

	ordered_unique< tag<TParamIDIndex>,
			composite_key<
				TParam,
				member<TParam,IDType,&TParam::ID>
			>,
			composite_key_compare<
				//std::less<std::string>
				customize_compare
			>
		>,

	ordered_non_unique< tag<TParamValidIndex>,
	member<TParam,bool,&TParam::IsValid> >
	>
>TParamSet;
typedef boost::multi_index::index<TParamSet,TParamIDIndex>::type TParamSetByID;
typedef boost::multi_index::index<TParamSet,TParamValidIndex>::type TParamSetByValid;


int _tmain(int argc, _TCHAR* argv[])
{
	TParamSet set;
	TParam *p1 = new TParam();
	strcpy_s(p1->ID, "aa");
	//p1->ID = "aa";
	set.insert(p1);

	TParam *p2 = new TParam();
	strcpy_s(p2->ID, "bb");
	//p2->ID = "bb";
	set.insert(p2);

	TParamSetByID::iterator it = set.find("aa");
	if (it != set.end())
		printf("found.");
	else
		printf("not found");

	return 0;
}
当然比较器使用std::less<std::string>也可以。
另外,上述例子仅作为验证Demo,实际代码中建议ID类型直接使用std::string,可以避免一些字符串被释放导致查询不到的情况,这时可以在自定义的比较函数中下断点进行调试。

boost composite_key_compare 自定义

分享到:
评论加载中,请稍后...
创APP如搭积木 - 创意无限,梦想即时!
回到顶部