#include "stdafx.h"
#include <list>
#include <string>
#include <boost/multi_index_container.hpp>
#include <boost/multi_index/ordered_index.hpp>
#include <boost/multi_index/identity.hpp>
#include <boost/multi_index/member.hpp>
#include <boost/lambda/lambda.hpp>
/*
标题:boost.Multi_Index库的使用
功能:类似std::map的容器,但是可以用多个关键词索引数据
描述:boost::multi_index::multi_index_container为容器内的数据建立多个视图
不同的索引字段(Key)对应不同的视图
boost::multi_index::multi_index_container经常可以采用不同的表达方式实现
同样的功能。
这里只列举一种能满足我们添加、删除、修改、检索记录的需求示例代码,有兴趣的话
可以通过参考资料中的官网地址得到如何使用其它方式达到这里功能需求的知识。
环境:Windows 8.1 64bit(英文版)
Visual Studio 2013 Professional with SP1
boost 1.55
注意:编写和template相关的代码一旦出错不会给出正确的错误位置
所以建议每完成一个函数,就写一个测试这个函数的函数。
最后更新日期:2014-5-10
应用范围:定制自己的内存数据库
参考资料:http://www.boost.org/doc/libs/1_55_0/libs/multi_index/doc/index.html
*/
#pragma region 定义 employee
//使用名字空间是为了防止数据类型名称冲突
namespace kagula
{
namespace datatype
{
//为了后面的代码能通过id和name名字取视图,定义了这两个结构
struct id{};
struct name{};
//employee是我们示例代码中表的结构
struct employee
{
int id;
std::wstring name;
employee(int id, const std::wstring& name) :id(id), name(name){}
//重载<运算符函数让后面名为id的视图按照id字段的升序排列
bool operator<(const employee& e)const{ return id<e.id; }
//重载<=运算符函数是为了得到指定id字段值范围的记录
bool operator<=(const employee& e)const{ return id<=e.id; }
//重载<<运算符函数是为了我们方便打印记录的内容
friend std::wostream& operator<<(std::wostream& os, const employee& dt);
};
std::wostream& operator<<(std::wostream& os, const employee& dt)
{
os << L"[" << dt.id << L',' << dt.name.c_str() << L"]";
return os;
}
//后面的代码,更新指定记录name字段的值要用到change_name类
//通过这个示例你可以知道如何修改符合搜索条件的,指定记录的任意字段值
struct change_name
{
change_name(const std::wstring& new_name) :new_name(new_name){}
void operator()(employee& e)
{
e.name = new_name;
}
private:
std::wstring new_name;
};
// 定义基于id和name关键词的多值索引集合类型
// 这个容器有id和name两个视图
typedef boost::multi_index::multi_index_container<
employee,
boost::multi_index::indexed_by<
//第一个视图,使用employee实例作为key,所以采用了emp
boost.Multi_Index库的使用
最新推荐文章于 2025-02-17 07:00:00 发布