C++生成随机字符串

最近给自己的网站搞一个相册,随机生成图片名字,生成100W个16位的名字,测试没重复,感觉还不错,生成的数字是均匀分布的cppreference

#include <random>
#include <iostream>
#include <unistd.h>
#include <unordered_set>
using namespace std;
char seed[64] = {
    
    
    '0','1','2','3','4','5','6','7','8','9',
    'A','B','C','D','E','F','G','H','I','J',
    'K','L','M','N','O','P','Q','R','S','T',
    'U','V','W','X','Y','Z','a','b','c','d',
    'e','f','g','h','i','j','k','l','m','n',
    'o','p','q','r','s','t','u','v','w','x',
    'y','z','\0','\0'
};
string getName(){
    
    
    static std::random_device rd;  // 将用于为随机数引擎获得种子
    static std::mt19937 gen(rd()); // 以播种标准 mersenne_twister_engine
    static std::uniform_int_distribution<> dis(0, 61);
    string name = "";
    for (int n = 0; n < 16; ++n){
    
    
        // 用 dis 变换 gen 所生成的随机 unsigned int 到 [0, 62] 中的 int
        int val = dis(gen);
        name += seed[val];
    }
    return name;
}
int main()
{
    
    
    unordered_set<string> us;
    while(us.size() < 1000000){
    
    
        string s = getName();
        if(us.count(s)){
    
    
            cout << "a o repeat~" << us.size() << endl;
            return -1;
        }
        us.emplace(s);
        // sleep(3);
    }
    return 0;
}


猜你喜欢

转载自blog.csdn.net/dxgzg/article/details/121913444