1. rand()

rand() % max 可以生成 [0, max) 范围的随机数,则

// 生成 [0, max]
int x = rand() % (max + 1);

// 生成 [1, max + 1) ,即 [1, max]
int x = 1 + rand() % (max);

// 生成 [min, max] 范围的随机数
int x = min + rand() % (max - min + 1);

2. STL

以下套用即可,具体解释见 cppreference

std::random_device rd;  //Will be used to obtain a seed for the random number engine
std::mt19937 gen(rd()); //Standard mersenne_twister_engine seeded with rd()
std::uniform_int_distribution<> distrib(1, 6); // 指定范围
 
 // Use `distrib` to transform the random unsigned int generated by gen into an int in [1, 6]
 // 生成 [1, 6] 范围的随机数
std::cout << distrib(gen) << endl;