我有一个向量int p=[n1,n2,n3]。 什么是最有效的方法来生成另一个向量,与P大小相同,称之为v1=[m1,m2,m3]。 步骤:
const int N = 10;
vector<int> p;
vector <double> b;
for ( int i =0; i<N ; i++)
{
Poiss = U.RandomPoisson(Lambda); // generate N Poissonian Random variables
Normal = U.RandomNormal(4000,7000); // generate N Normal Random variable
p.push_back(Poiss);
b.push_back(Normal);
}
// iterate over P and use each element of p call it p[i] as the size of a new random vector with size p[i] call it vec[p[i]]. Take the sum of vec[p[i]] and add to a new vector call it V. The Final size of V is the same as P
for ( auto &i : p )
{
do some stuff...
}
您可能需要以下内容:
vector<vector<int>> vec;
vector<int> v;
v.reserve(p.size());
for (auto &&i : p) {
vector<int> temp(i);
for (auto &&j : temp)
j = U.RandomNormal(4000, 7000);
v.push_back(accumulate(temp.begin(), temp.end(), 0));
vec.push_back(move(temp));
}
代替
for (auto &&j : temp)
j = U.RandomNormal(4000, 7000);
您可以直接使用:
std::generate(temp.begin(), temp.end(), [&U] () { return U.RandomNormal(4000, 7000); });
如果不需要vec
,即只需要v
中的值,则执行如下操作:
vector<int> v;
v.reserve(p.size());
for (auto &&i : p) {
int sum = 0;
for (int j = 0; j < i; ++j)
sum += U.RandomNormal(4000, 7000);
v.push_back(sum);
}