我必须创建一个数据结构来存储1万亿用户的生日。怎么做?
如果我使用struct数据类型,那么它将需要6个字节。
struct{
int day,month,year;
}
所以6 * 1万亿= 6万亿字节?
有没有任何优化方式或其他方式来做到这一点?
答案 0 :(得分:1)
假设每天5位,月份4位和年份12位,每个用户需要21位。填充到8位的倍数,每个条目有24位= 3字节。
这意味着,您需要3 TB之类的东西来存储您的所有数据(如果我没有计算错误)。
答案 1 :(得分:0)
基于Hannu的答案:(每天5位,月份4位,年份7位)
const unsigned long int n = 1e2;
// store (n * 2 bytes)
unsigned short birthdays[n];
static_assert( sizeof(short) == 2, "failure." );
// user input
int day = 31; // requirement: 5 bits
int month = 12; // requirement: 4 bits
int year = 127; // requirement: 7 bits. actual year = 1940(starting year) + 127 = 2067 (max year)
// store
// birthdays[0] = day + month * 32 + year * 512;
birthdays[0] = day + (month << 5) + (year << 9);
// how it looks
std::bitset<16> binary(birthdays[0]);
cout << "raw record: " << birthdays[0] << " (binary view = " << binary << ")" << endl;
// retrieve
day = (unsigned short)(birthdays[0] << 11) >> 11;
month = (unsigned short)(birthdays[0] << 7) >> 12;
year = (birthdays[0] >> 9) + 1940;
cout << "day = " << day << endl;
cout << "month = " << month << endl;
cout << "year = " << year << endl;