您的位置:首页 > 编程语言 > C语言/C++

c/c++生成不重复的字符串(6个字符组成,可表示的个数可以扩充),简易版数据库主键

2015-09-29 11:08 531 查看
#include<stdio.h>
#include<stdint.h>
#include<math.h>

#include<string>
#include<iostream>
#include<vector>
using namespace std;

string random_uuid_6();

#define MAX 10000

int main()
{
vector<string> vec;
for(int i=0;i<MAX;++i)
{
string str=random_uuid_6();
vec.push_back(str);
cout<<str<<endl;
cout<<str<<endl;
}

for(vector<string>::iterator it=vec.begin();it!=vec.end();++it)
{
size_t count=0;
for(vector<string>::iterator ij=vec.begin();ij != vec.end();++ij)
{
if(*it == * ij)
{
count++;
}
if(count>=2 )
{
cout<<"count"<<count<<" "<<"有重复"<<endl;
return -1;
}
cout<<count<<endl;
}
}
return 0;
}

/************************************************************************/
/*                                                                     */
/************************************************************************/
string random_uuid_6()
{
char result[7]={0};
char * result_tmp=&result[5];
uint32_t factor_encry=2863314058;  //rao luan yin zi
static uint32_t flag=0;

char chs[]= { '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','+','-'};   //64jinzhi
++flag;

//取62进制,以6位一个单位换算
uint32_t factor=(int)(pow(2.0,0)+pow(2.0,1)+pow(2.0,2)+pow(2.0,3)+pow(2.0,4)+pow(2.0,5));
for(int i=0;i<6;++i)
{
uint32_t data=pow(2.0,i*6)*factor;
uint32_t flag_encry=factor_encry ^ flag;
uint32_t tmp=data & flag_encry;
tmp=tmp >> i*6;
*result_tmp--=chs[tmp];
}
return string(result);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: