相关疑难解决方法(0)

根据value_type调用适当的构造函数:integer或float

我有一个函数,使用均匀分布填充具有min和max之间随机值的容器.

#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 << " "; }
}
Run Code Online (Sandbox Code Playgroud)

更换std::vector<float>std::vector<int>不工作,因为我将不得不使用std::uniform_int_distribution来代替.是否有一种简单而优雅的方法来根据value_type参数选择正确的构造函数?

我到目前为止尝试使用std::numeric_limits<typename …

c++ templates c++11

5
推荐指数
2
解决办法
345
查看次数

标签 统计

c++ ×1

c++11 ×1

templates ×1