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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3247861/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 12:25:37  来源:igfitidea点击:

Example of UUID generation using Boost in C++

c++boostuuidboost-uuid

提问by Nikola

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.

我只想生成随机的 UUID,因为我的程序中的实例具有唯一标识符非常重要。我查看了Boost UUID,但我无法生成 UUID,因为我不明白要使用哪个类和方法。

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

如果有人能给我任何如何实现这一目标的例子,我将不胜感激。

回答by Georg Fritzsche

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

回答by Nikko

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:

Georg Fritzsche 的回答是可以的,但可能有点误导。如果您需要多个 uuid,您应该重用生成器。也许这样更清楚:

#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;
}