使用C类型uuid_t作为std :: map中的键的最佳方法是什么?

时间:2011-11-20 08:59:00

标签: c++ dictionary std uuid stdmap

这是在地图中提供唯一键的合适方式吗?换句话说,键是由uuid中包含的唯一值构成的,还是由指向uuid_t结构的指针构成的?一个侧面的问题是,当我不关心容器内的按键排序时,是否有更高效的容器?

#include <uuid/uuid.h>

int main(int argc, char **argv)
{    
   std::map<uuid_t,int> myMap;         

   uuid_t id1;
   uuid_t id2;

   uuid_generate( (unsigned char *)&id1 );  
   uuid_generate( (unsigned char *)&id2 );

   myMap[id1] = 5;
   myMap[id2] = 4;

}

3 个答案:

答案 0 :(得分:5)

我想使用第三方C结构的最佳方法是通过友好的功能使用它们。所以如果你想在STL中使用uuid_t,我建议你为这个结构创建一些C ++接口/包装器,如

struct Uuid {
  uuid_t uuid;
  Uuid(const Uuid &other) { uuid_copy(uuid, other.uuid); }
  Uuid(const uuid_t other_uuid) { uuid_copy(uuid, other_uuid); }
  void generateInplace() { uuid_generate(uuid); }
  static Uuid generate() { Uuid wrapped; uuid_generate(wrapped.uuid); return wrapped; }
  bool operator<(const Uuid &other) { return uuid_compare(uuid, other.uuid) < 0; }
  bool operator==(const Uuid &other) { return uuid_compare(uuid, other.uuid) == 0; }
  // ...
};

那应该向你隐瞒uuid_t不是结构而是指向数组的指针(即typedef unsigned char uuid_t[16])。

注意:有boost version of uuid library

答案 1 :(得分:3)

STL容器始终包含对象的副本,并且也适用于映射键。

支持此功能的最简单方法是为地图使用自定义比较器。

struct UUIDComparator
{
    bool operator()(const uuid_t &a, const uuid_t &b)
    {
        //compare and return a < b
    }
};
std::map<uuid_t, int, UUIDComparator> map;

另一个有争议的解决方案是将uuid_t转换为std::pair<uint64_t, uint64_t>,因为两种类型都是128位宽,并且AFAICT,布局兼容。 std::pair可直接用作地图密钥。

std::map<std::pair<uint64_t, uint64_t>, int, UUIDComparator> map;

答案 2 :(得分:1)

更简单:uuid_unparse(...)将其转换为char *(37个字符长),然后你可以将一个字符串包裹起来......

相关问题