简体   繁体   English

在C ++中使用Boost生成UUID的示例

[英]Example of UUID generation using Boost in C++

I want to generate just random UUID's, as it is just important for instances in my program to have unique identifiers. 我想生成随机的UUID,因为对于我的程序中的实例而言,它具有唯一标识符非常重要。 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. 我查看了Boost UUID ,但我无法生成UUID,因为我不明白要使用哪个类和方法。

I would appreciate if someone could give me any example of how to achieve this. 如果有人能给我任何如何实现这一目标的例子,我将不胜感激。

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 7feb24af-fc38-44de-bc38-04defc3804de

The answer of Georg Fritzsche is ok but maybe a bit misleading. Georg Fritzsche的答案还可以,但可能有点误导。 You should reuse the generator if you need more than one uuid. 如果您需要多个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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM