views:

118

answers:

1

Hi everyone,

I'm quite a newbie in c++ and I want to generate just random UUID's, as it is just important for instances in my program to have unique identifiers. I looked into Boost UUID, but I can't manage to generate the UUID because I don't understand which class and method to use.

In Java it is as simple as java.util.UUID.randomUUID().

So I would appreciate if someone could give me any example of how to achieve this.

Thank you!

+6  A: 

A basic example:

#include <boost/uuid/uuid.hpp>            // uuid class
#include <boost/uuid/uuid_generators.hpp> // generators
#include <boost/uuid/uuid_io.hpp>         // streaming operators etc.

int main() {
    boost::uuids::uuid uuid = boost::uuids::random_generator()();
    std::cout << uuid << std::endl;
}

Example output:

7feb24af-fc38-44de-bc38-04defc3804de

Georg Fritzsche
Thank you! I was confused by two pairs of brackets.:)
Nikola
And how would you assign it to a string? Because I have a common base for every instance and I would need to concatenate UUID to a base. Thanks again!
Nikola
@nik: Use the [streaming support](http://www.boost.org/doc/libs/1_43_0/libs/uuid/uuid.html#boost/uuid/uuid_io.hpp) - there is a `stringstream` example. Or let `boost::lexical_cast<std::string>(uuid)` do that for you.
Georg Fritzsche
As for the double parantheses: The first constructs an instance of `random_generator`, the second uses `operator()` on that instance. You should save the generator and call `operator()` on it if you want to generate more than one uuid: `random_generator rg; uuid ui = rg();`
Georg Fritzsche