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

我只想生成随机的 UUID,因为对于我的程序中的实例来说,拥有唯一的标识符非常重要。我查看了 提升 UUID,但是无法生成 UUID,因为我不知道要使用哪个类和方法。

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

88827 次浏览

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

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