Converting zhash_t to std::map

Problem:

You have a hash data structure represented by CZMQ’s zhash_t (see the zhash_t documentation for further information).

In order to be able to use it more conveniently in C++, you intend to convert said zhash_t to a std::map<std::string, std::string>.

Solution:

This example assumes the zhash_t only contains cstrings as keys and values. If that is not the case, you can change the example below according to the specific data structures in use.

You can use this utility function which leverages C++11 emplace semantics for efficiency and readability reasons:

/*
 * zhash_t -> std::map conversion utility
 * Written by Uli Koehler (techoverflow.net)
 * Released under the public domain
 */
#include <map>
#include <string>
#include <czmq.h>

/**
 * Converts a zhash to a std::map
 * Precondition (not checked): Any key and value must represent a 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;
}

If you can’t use C++11, just change ret-emplace(key, value); in line 21 to ret[std::string(key)] = std::string(value);.