我想为我的应用程序生成UUID,以区分我的应用程序的每个安装.我想在没有boost库支持的情况下使用C++生成这个UUID.如何使用其他一些开源库生成UUID?
注意:我的平台是windows
Sas*_*yal 24
如果您使用的是现代 C++,则可以这样做。
#include <random>
#include <sstream>
namespace uuid {
static std::random_device rd;
static std::mt19937 gen(rd());
static std::uniform_int_distribution<> dis(0, 15);
static std::uniform_int_distribution<> dis2(8, 11);
std::string generate_uuid_v4() {
std::stringstream ss;
int i;
ss << std::hex;
for (i = 0; i < 8; i++) {
ss << dis(gen);
}
ss << "-";
for (i = 0; i < 4; i++) {
ss << dis(gen);
}
ss << "-4";
for (i = 0; i < 3; i++) {
ss << dis(gen);
}
ss << "-";
ss << dis2(gen);
for (i = 0; i < 3; i++) {
ss << dis(gen);
}
ss << "-";
for (i = 0; i < 12; i++) {
ss << dis(gen);
};
return ss.str();
}
}
Run Code Online (Sandbox Code Playgroud)
Yuv*_*val 12
如评论中所述,您可以使用UuidCreate
#pragma comment(lib, "rpcrt4.lib") // UuidCreate - Minimum supported OS Win 2000
#include <windows.h>
#include <iostream>
using namespace std;
int main()
{
UUID uuid;
UuidCreate(&uuid);
char *str;
UuidToStringA(&uuid, (RPC_CSTR*)&str);
cout<<str<<endl;
RpcStringFreeA((RPC_CSTR*)&str);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
Cap*_*man 12
如果你只是想要一些随机的东西,我写了这个小函数:
string get_uuid() {
static random_device dev;
static mt19937 rng(dev());
uniform_int_distribution<int> dist(0, 15);
const char *v = "0123456789abcdef";
const bool dash[] = { 0, 0, 0, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 0, 0, 0 };
string res;
for (int i = 0; i < 16; i++) {
if (dash[i]) res += "-";
res += v[dist(rng)];
res += v[dist(rng)];
}
return res;
}
Run Code Online (Sandbox Code Playgroud)
2021年,我建议使用单头库stduuid。它是跨平台的,并且不会带来任何不需要的依赖项。
uuid.h从项目的 github 页面下载,然后一个最小的工作示例是:
#include <iostream>
#include <string>
#define UUID_SYSTEM_GENERATOR
#include "uuid.h"
int main (void) {
std::string id = uuids::to_string (uuids::uuid_system_generator{}());
std::cout << id << std::endl;
}
Run Code Online (Sandbox Code Playgroud)
有关各种选项和生成器的更多详细信息和文档,请参阅该项目的 github 页面。
所述OSSP-UUID库可以生成UUID,并具有C ++绑定。
使用起来似乎非常简单:
#include <uuid++.hh>
#include <iostream>
using namespace std;
int main() {
uuid id;
id.make(UUID_MAKE_V1);
const char* myId = id.string();
cout << myId << endl;
delete myId;
}
Run Code Online (Sandbox Code Playgroud)
请注意,它分配并返回一个 C 风格的字符串,调用代码必须释放该字符串以避免泄漏。
另一种可能性是 libuuid,它是 util-linux 包的一部分,可从ftp://ftp.kernel.org/pub/linux/utils/util-linux/ 获得。任何 Linux 机器都已经安装了它。它没有 C++ API,但仍然可以使用 C API 从 C++ 调用。