【问题标题】:C++ Vector iterationC++ 向量迭代
【发布时间】:2020-11-01 18:47:31
【问题描述】:

我有一个 int P=[n1,n2,n3] 的向量。生成另一个与 P 大小相同的向量的最有效方法是什么,称为 v1=[m1,m2,m3]。步骤:

  1. 向量 P[N], N , 包含n0, n1, n2
  2. 对于 N 中的每个 n_i,生成一个大小为 n0,然后为 n1,n2 的正态随机变量向量
  3. 独立取每个新向量的和,sum(n0), sum(n1), sum(n2)
  4. 创建一个向量 v1[m1,m2,m3]。对于“v1”中的每个 i 都包含上一步中随机数的总和。
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...
}

【问题讨论】:

  • 您是否尝试过编写任何代码来解决此问题?如果您展示一些输入和所需输出的示例,也会很有帮助。
  • 您应该先尝试编写一些代码。现在,这似乎更像是“给我一些代码”这样的问题。还要衡量这是否真的是一个瓶颈。通常也没有最有效的方法,但您需要妥协,例如使用更多内存但更少时间,反之亦然。
  • 到目前为止,您在提供的代码中实现了什么,还是只是“伪”?
  • 这是实际的实现,不知道你说的“伪”是什么意思
  • 忘记作为类实例的 U.,它是 RandomPoisson 和 RandomNormal 的成员。

标签: c++ arrays loops vector iterator


【解决方案1】:

你可能需要这样的东西:

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);
}

【讨论】:

  • 谢谢你,brc-dd 和休息。
猜你喜欢
  • 2013-12-16
  • 1970-01-01
  • 1970-01-01
  • 2016-01-10
  • 1970-01-01
  • 1970-01-01
  • 2013-02-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多