c++ - std::piecewise_constant_distribution 和 std::vector 的问题

标签 c++ random c++11 distribution piecewise

给定一堆字符串,我正在尝试创建一个程序,该程序可以根据我的输入通过加权分布来模拟伪随机行为。

到目前为止我想出了这个

#include <iostream>
#include <random>
#include <type_traits>
#include <map>
#include <vector>
#include <string>
#include <initializer_list>

#define N 100

int main()
{
    std::vector<std::string> interval{"Bread", "Castle", "Sun"};
    std::vector<float> weights { 0.40f, 0.50f, 0.10f };
    std::piecewise_constant_distribution<> dist(interval.begin(),
                                                interval.end(),
                                                weights.begin());

    std::random_device rd;
    std::mt19937 gen(rd()) ;

    for(int i = 0; i<N;i++)
    {
        std::cout << dist(gen) << "\n";
    }

    return(0);

}

但这东西不起作用,我不知道为什么,通常使用 std::piecewise_constant_distribution ,根据在线示例,它与 std::arrays >,但我尝试使用 std::vector 来实现它,这是我发现的主要区别。

使用 Clang++ 时,错误的输出是

/usr/bin/../lib/gcc/x86_64-linux-gnu/4.7/../../../../include/c++/4.7/bits/random.tcc:2409:10: error: no matching member function for
      call to 'push_back'
                _M_int.push_back(*__bbegin);
                ~~~~~~~^~~~~~~~~

但我无法理解它,因为我的代码中没有显式的 .push_back ,我也无法从其中得到什么,因为调试模板类是一场噩梦,我'我刚刚从这个开始。

有人知道为什么代码不起作用吗?

最佳答案

std::piecewise_constant_distribution 的默认结果类型是 RealType(此处为 double)。看起来您正在尝试从 3 个具有不同权重的 string 选项中进行选择,但这不是 std::piecewise_constant_distribution 的用途。它旨在根据给定权重的数字间隔生成统一的随机值。如果您修改示例并将 interval 更改为:

std::vector<double> interval {1, 3, 5, 10, 15, 20};

一切都会顺利编译。从表面上看,您需要 std::discrete_distribution:

...

std::vector<std::string> interval{"Bread", "Castle", "Sun"};
std::vector<float> weights { 0.40f, 0.50f, 0.10f };
std::discrete_distribution<> dist(weights.begin(), weights.end());

std::mt19937 gen(rd());

for(int i = 0; i<N;i++)
{
    std::cout << interval[dist(gen)] << "\n";
}

...

关于c++ - std::piecewise_constant_distribution 和 std::vector 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16513628/

相关文章:

C++/mysql 连接器 - 对 get_driver_instance 的 undefined reference - 已经尝试过简单的东西

c++ - 快速读取带有 float 的文本文件

java - 猜谜游戏中的随机数

c++ - 使用连续种子生成均匀随机数?

c++ - 默认的 Move 构造函数是否定义为 noexcept?

c++ - C/C++ 宏扩展为参数,参数为字符串

c++ 将 char* 的 ascii 字符转换为 unix 文件名

c - 在 Linux 上用 C 获取每次引导随机种子的可移植方法

java - 如何在 MySQL 中创建不重复的随机用户 ID?

c++ - 友元函数和声明