c – std :: generate不能在std :: vector上工作
作者:互联网
#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.2和g 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
在这种情况下,我没有任何关于可能出错的线索或想法.
解决方法:
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.
标签:stl-algorithm,c,g 来源: https://codeday.me/bug/20190723/1509394.html