【问题标题】:ISO C++ forbids declaration of 'uniform_real_distribution' with no typeISO C++ 禁止声明没有类型的“uniform_real_distribution”
【发布时间】:2015-05-06 23:05:33
【问题描述】:
#ifndef _RNG_H
#define _RNG_H

#include <random>

class RNG {
public:
  RNG() :
    _generator(_default_seed) { }

  RNG(uint32_t seed):
    _generator(seed) { }

  double operator()();

private:
  std::mt19937 _generator;
  static std::uniform_real_distribution<> _urd;
  static const int _default_seed;
};

#endif // _RNG_H

我正在尝试封装与包装类一起使用的随机数生成器。但是当尝试编译上面的代码时,我得到了以下错误:

rng.h:37: 错误:ISO C++ 禁止声明没有类型的“uniform_real_distribution”

rng.h:37: 错误:'::' 的使用无效

rng.h:37: 错误:预期为 ';'在'之前

但我只是想按照http://en.cppreference.com/w/cpp/numeric/random/uniform_real_distribution 中给出的示例进行操作

【问题讨论】:

  • 无法重现:ideone.com/7O6D2M 是否在-std=c++11 支持下编译?
  • C(和 C++)不允许用户使用 _Leading_underscore_capital 名称;注意_RNG_H
  • @mariner:您的问题很可能来自 GCC 4.4.7 没有完全实现 C++11。
  • @BillyONeal:此类标识符并非完全不允许。它们保留给实现,这使得在您自己的代码中定义它们未定义的行为。通常,只要标识符碰巧没有与任何东西发生冲突,编译器就不会抱怨。底线:将_RNG_H 更改为RNG_H 是个好主意,但它不太可能是观察到的错误的原因。
  • @Kieth:我从未打算声称这是观察到错误的原因(这就是为什么我将其作为评论而不是答案)

标签: c++


【解决方案1】:

G++ 4.4.7 实现了Technical Report 1's random,而不是 C++11 的随机。

这意味着没有std::uniform_real_distribution类型。

您可以编写如下所示的代码:

#include <random>
#include <iostream>

int main() {
    std::random_device rng;
    double x = std::uniform_real<>()(rng);
    printf("%lf\n", x);
}

虽然我怀疑它有问题,因为它返回的值远大于范围 [0, 1),这是我理解的限制应该是什么。

【讨论】:

    【解决方案2】:
    #if defined __GNUC__
      #define GCC_VERSION (__GNUC__ * 10000 \
                               + __GNUC_MINOR__ * 100 \
                               + __GNUC_PATCHLEVEL__)
      #if GCC_VERSION < 40300
        #include <tr1/random>
      #else
        #include <random>
      #endif
    #else
      #include <random>
    #endif
    
    #include <iostream>
    #include <sys/types.h>
    
    typedef std::mt19937                                        generator_t;
    typedef std::uniform_real<double>                           distribution_t;
    typedef std::variate_generator<generator_t, distribution_t> variate_t;
    
    int main() {
        generator_t sparfun_rand;
        variate_t sparfun_rand_unif(sparfun_rand, distribution_t(0.0,1.0));
        distribution_t dist(0.0, 1.0);
        for (int i = 0; i < 10 ; i++) {
          std::cout << dist(sparfun_rand_unif) << std::endl;
        }
    }
    

    让它与带有 -std=c++0x 标志的 gcc 4.4.7 一起工作。

    【讨论】:

      猜你喜欢
      • 2011-08-21
      • 1970-01-01
      • 1970-01-01
      • 2015-10-31
      • 2020-12-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多