将 zhash_t 转换为 std::map
问题:
你有一个由 CZMQ 的 zhash_t 表示的哈希数据结构(更多信息请参见 zhash_t 文档)。
为了能在 C++ 中更方便地使用它,你打算将所述 zhash_t 转换为 std::map<std::string, std::string>。
解决方案
此示例假设 zhash_t 只包含 cstring 作为键和值。如果不是这种情况,你可以根据使用的特定数据结构更改下面的示例。
你可以使用此实用函数,它出于效率和可读性原因利用了 C++11 emplace 语义:
zhash_to_map.cpp
/*
* zhash_t -> std::map 转换工具
* 由 Uli Koehler (techoverflow.net) 编写
* 在公共领域发布
*/
#include <map>
#include <string>
#include <czmq.h>
/**
* 将 zhash 转换为 std::map
* 前提条件(未检查):任何键和值必须表示 cstring
*/
inline std::map<std::string, std::string> zhashToMap(zhash_t* hash) {
std::map<std::string, std::string> ret;
zlist_t* headersKeys = zhash_keys (hash);
for(char* key = (char*) zlist_first(headersKeys);
key != NULL;
key = (char*)zlist_next(headersKeys)) {
char* value = (char*)zhash_lookup(hash, key);
ret.emplace(key, value);
}
zlist_destroy(&headersKeys);
return ret;
}如果你不能使用 C++11,只需将第 21 行的 ret-emplace(key, value); 更改为 ret[std::string(key)] = std::string(value);。
Check out similar posts by category:
C/C++
If this post helped you, please consider buying me a coffee or donating via PayPal to support research & publishing of new posts on TechOverflow