我有一个函数,它使用均匀分布将最小值和最大值之间的随机值填充到容器中。
#include <iostream>
#include <random>
#include <algorithm>
#include <vector>
template<typename TContainer>
void uniform_random(TContainer& container,
const typename TContainer::value_type min,
const typename TContainer::value_type max) {
std::random_device rd;
std::mt19937 gen(rd());
// Below line does not work with integers container
std::uniform_real_distribution<typename TContainer::value_type> distribution(min, max);
auto lambda_norm_dist = [&](){ return distribution(gen); };
std::generate(container.begin(), container.end(), lambda_norm_dist);
}
int main() {
std::vector<float> a(10);
uniform_random(a,0,10);
for (auto el : a) { std::cout << el << " "; }
}
替换 std::vector<float>
与 std::vector<int>
不起作用,因为我必须使用 std::uniform_int_distribution
反而。
是否有一种简单而优雅的方法来根据 value_type 参数选择正确的构造函数?
到目前为止,我一直在尝试使用 std::numeric_limits<typename TContainer::value_type>::is_integer
没有成功。
最佳答案
在 C++14(或稍作改动的 C++11)中,您可以通过这种方式创建一个 uniform_distribution
类型别名:
template <typename ValueType>
using uniform_distribution = std::conditional_t<
std::is_floating_point<ValueType>::value,
std::uniform_real_distribution<ValueType>,
std::uniform_int_distribution<ValueType>
>;
用法:
uniform_distribution<typename TContainer::value_type> distribution(min, max);
关于c++ - 根据 value_type 调用适当的构造函数 : integer or float,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29747259/