Example of UUID generation using Boost in C++

C++BoostUuidBoost Uuid

C++ Problem Overview


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.

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

C++ Solutions


Solution 1 - C++

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

Solution 2 - C++

The answer of Georg Fritzsche is ok but maybe a bit misleading. You should reuse the generator if you need more than one uuid. Maybe it's clearer this way:

#include <iostream>

#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::random_generator generator;

    boost::uuids::uuid uuid1 = generator();
    std::cout << uuid1 << std::endl;

    boost::uuids::uuid uuid2 = generator();
    std::cout << uuid2 << std::endl;

	return 0;
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionNikolaView Question on Stackoverflow
Solution 1 - C++Georg FritzscheView Answer on Stackoverflow
Solution 2 - C++NikkoView Answer on Stackoverflow