std :: generate不能在std :: vector上工作

时间:2013-06-16 12:49:37

标签: c++ g++ stl-algorithm

#include <iostream>
#include <random>
#include <algorithm>

int main()
{
  std::mt19937 mt;
  std::uniform_int_distribution<int> d(0, 255);
  int l = 500;
  std::vector<int> k(l);
  std::generate(k.begin(), k.end(), d(mt));
  return(0);
}

尝试同时使用g++ 4.7.2g++ 4.8.1进行编译

g++ -std=c++11 main.cpp

报告的错误是

In file included from /usr/include/c++/4.7/algorithm:63:0,
                 from main.cpp:3:
/usr/include/c++/4.7/bits/stl_algo.h: In instantiation of ‘void std::generate(_FIter, _FIter, _Generator) [with _FIter = __gnu_cxx::__normal_iterator<int*, std::vector<int> >; _Generator = int]’:
main.cpp:11:42:   required from here
/usr/include/c++/4.7/bits/stl_algo.h:5083:2: error: ‘__gen’ cannot be used as a function

对于这种情况下可能出现的问题,我没有任何线索或想法。

1 个答案:

答案 0 :(得分:9)

std::generate获取一个函数对象并将其返回值应用于序列容器。但std::uniform_int_distribution<T>::operator ()不返回函数对象,它实际上生成随机值并返回它。如果要传递函子,请使用lambda:

std::generate(k.begin(), k.end(), [&] { return d(mt); });
//                                ^^^^^^^^^^^^^^^^^^^^^

Here is a working example of your program.