如何用msgpack-c打包多键地图
how to pack multi-key map with msgpack-c
我正在尝试使用msgpack(在c版本中,而不是c++)来替换我们自己的序列化方法,该方法是基于主xml的。打包一些普通的数据是非常直接的。然而,我们有很多基于k-v的结构,比如
struct Table {
struct Key {
// Multi-keys
int key1;
int key2;
};
struct Attr {
// Attributes
int attr1;
bool attr2;
char[8] attr3;
};
}
如何在msgpack-c中用msg_pack_map打包多关键字表?(不幸的是,我们的系统被异常禁用,所以我不能使用c++版本"msgpack.hpp")
我的代码片段:
msgpack_sbuffer sbuf;
msgpack_sbuffer_init(&sbuf);
msgpack_packer pk;
msgpack_packer_init(&pk, &sbuf, msgpack_sbuffer_write);
msgpack_packer_map(&pk, 10) // 10 pairs
for(int i= 0; i<10; ++i) {
// key
msgpack_pack_array(&pk, 2);
msgpack_pack_int(&pk, i);
msgpack_pack_int(&pk, 100+i);
// attr
msgpack_pack_array(&pk, 3);
msgpack_pack_int(&pk, 1);
msgpack_pack_true(&pk);
msgpack_pack_str(&pk, 7);
msgpack_pack_str_body(&pk, "example");
}
我假设在msgpack中,我们必须使用msgpack_pack_array来打包结构。
我的代码正确吗?或者有更好的方法吗?
我更新了您的代码片段,并添加了测试代码。
参见:
http://melpon.org/wandbox/permlink/RuZKLmzwStHej5TP
#include <msgpack.h>
#include <msgpack.hpp>
#include <map>
#include <iostream>
struct Key {
// Multi-keys
int key1;
int key2;
MSGPACK_DEFINE(key1, key2);
};
inline bool operator<(Key const& lhs, Key const& rhs) {
if (lhs.key1 < rhs.key1) return true;
if (lhs.key1 > rhs.key1) return false;
if (lhs.key2 < rhs.key2) return true;
return false;
}
struct Attr {
// Attributes
int attr1;
bool attr2;
std::string attr3;
MSGPACK_DEFINE(attr1, attr2, attr3);
};
int main() {
msgpack_sbuffer sbuf;
msgpack_sbuffer_init(&sbuf);
msgpack_packer pk;
msgpack_packer_init(&pk, &sbuf, msgpack_sbuffer_write);
msgpack_pack_map(&pk, 10); // 10 pairs
for(int i= 0; i<10; ++i) {
// key
msgpack_pack_array(&pk, 2);
msgpack_pack_int(&pk, i);
msgpack_pack_int(&pk, 100+i);
// attr
msgpack_pack_array(&pk, 3);
msgpack_pack_int(&pk, 1);
msgpack_pack_true(&pk);
msgpack_pack_str(&pk, 7);
msgpack_pack_str_body(&pk, "example", 7);
}
{
auto upd = msgpack::unpack(sbuf.data, sbuf.size);
std::cout << upd.get() << std::endl;
auto tbl = upd.get().as<std::map<Key, Attr>>();
}
msgpack_sbuffer_destroy(&sbuf);
}
这是一个c++代码,但我在打包部分使用c API。您可以检查未打包的msgpack对象。它也被成功地转换为C++映射。
以下是C API文档:https://github.com/msgpack/msgpack-c/wiki/v1_1_c_overview
相关文章:
- 基于多个条件处理地图中的所有元素
- 如何遍历多个地图并获取它们的值? - C++
- 如何在C++的多维地图中实现常量正确性
- 在地图键的矢量中查找多个字符串
- 在编译时间检查模板参数类型是否设置或多键,并且容器的元素类型是算术的
- SDL 多键按下问题
- C++中的多键自定义排序
- 使用单词键将多个行号的向量添加到我的地图中
- 将项目存储在地图中的多个键下
- 使用可变参数模板的多键映射
- 如何使用其中一个键搜索具有多个键的地图
- 有没有一张多维地图
- C++容器存储(insert/get/remove)结构,具有整数值的多键是指针
- 如何用msgpack-c打包多键地图
- 使用多关键字地图进行有效搜索
- 在多映射中,当两个迭代器持有具有映射到不同Value的相同键的值时.我们如何才能在地图上找到它们中的哪一个在另一个之前
- 具有OR搜索功能的多键容器
- 设计数据结构来存储多键对象集,以便能够收集和遍历该集的超平面
- 合并多个地图
- C++多维地图:如何访问'inner'地图?