c++ - C++ 向量迭代
问题描述
我有一个 int P=[n1,n2,n3] 的向量。生成另一个与 P 大小相同的向量的最有效方法是什么,称为 v1=[m1,m2,m3]。步:
- 向量 <int> P[N], N ,包含 n0, n1, n2
- 对于 N 中的每个 n_i ,生成一个大小为 n0 的正常随机变量向量,然后是 n1, n2
- 独立取每个新向量的和,sum(n0), sum(n1), sum(n2)
- 创建一个向量 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...
}
解决方案
你可能需要这样的东西:
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);
}
推荐阅读
- python-3.x - jinja2.exceptions.TemplateNotFound:模板/entry.html
- sql - 图表类中的 SQL 数据库架构
- javascript - 重试时客户端连接未正确关闭
- javascript - Chart,js Pie Chart 可以调整饼图和图例的差距吗
- swift - Swift 计时器没有在精确的时间执行
- node.js - IISNode WebSocket 从远程浏览器抛出错误“到 'ws://somewebsite.com/sampleServer' 的 WebSocket 连接失败:帧头无效”
- reactjs - React 类组件的问题与使用 onScroll Init 的 React Hook 的行为不同
- php - 如何在 laravel 5,7 中自定义登录
- reactjs - 如何从 API 中解构对象?
- c# - 有人可以解释一下这个服务器程序是如何在每次连接后关闭它的套接字的吗?我怎样才能让插座保持打开状态?