What is the best way to use type u uuid_t as a key in STL std :: map?

Is this a suitable way to provide unique keys on a card? In other words, is the key from a unique value contained in uuid, or is it made from a pointer to a uuid_t structure? The side question is, is there a more efficient container when I do not need to arrange the keys inside the container?

#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; } 
+4
source share
3 answers

I think the best way to use third-party C structures is to use them through their friendly functions. Therefore, if you want to use uuid_t in STL, I would suggest you create some kind of C ++ interface / shell for this structure, for example

 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; } // ... }; 

This should hide from you the fact that uuid_t not a structure, but a pointer to an array (ie typedef unsigned char uuid_t[16] ).

Note: increase the version of the uuid library

+4
source

STL containers always contain copies of an object, and this also applies to map keys.

The easiest way to support this is to use a custom comparator for the map.

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

Another slightly inconsistent solution would be to convert uuid_t to std::pair<uint64_t, uint64_t> , since both types are 128 bits wide and AFAICT compatible with layouts. And std::pair can be used directly as map keys.

 std::map<std::pair<uint64_t, uint64_t>, int, UUIDComparator> map; 
+3
source

Simplification: uuid_unparse (...) converts it to char * (37 characters long), after which you can wrap the string around ...

+1
source

Source: https://habr.com/ru/post/1382125/


All Articles