跳到正文

算法·理论

随机数模板——超越rand

#SUSPENDED#约 2 分钟
原文
文章信息与版本

文章信息

发布
2026年3月29日
收录
2026年4月6日
更新
2026年11月12日
篇幅
约 2 分钟

版本

  1. v1当前

无AI!

C++
thread_local static mt19937 rnd(chrono::duration_cast<chrono::nanoseconds>
	(chrono::system_clock::now().time_since_epoch()).count());
template<typename T>
T random(T L, T R){
	static_assert(is_arithmetic_v<T>
	, "Template parameter 'T' must be an arithmetic type.");
	if constexpr (is_integral_v<T>){
		#ifdef _DEBUG
			if (L > R){
				throw invalid_argument("For integral types,\
				 L must not exceed R.");
			}
		#endif
		uniform_int_distribution<T> dist(L, R);
		return dist(rnd);
	}else if constexpr (is_floating_point_v<T>){
		#ifdef _DEBUG
			if (L >= R){
				throw invalid_argument("For floating-point types,\
				 L must be strictly less than R.");
			}
			if (!isfinite(L) || !isfinite(R)){
				 throw invalid_argument("Bounds must be finite numbers.");
			}
		#endif
		uniform_real_distribution<T> dist(L, R);
		return dist(rnd);
	}
}
原文