gpt4 book ai didi

c++ - std::generate 不适用于 std::vector

转载 作者:太空狗 更新时间:2023-10-29 19:58:51 25 4
gpt4 key购买 nike

#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

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

最佳答案

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.

关于c++ - std::generate 不适用于 std::vector,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17133518/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com