我正在尝试计算向量向量内的一系列元素的能量。一旦特定元素具有正确的能量,它就会被推入另一个向量向量。这是一个示例,因为很难解释:
bool energy(const std::vector<double> &vals)
{
float sum = 0.0;
for(unsigned i=0; (i < vals.size()); i++)
{
sum += (vals[i]*vals[i]);
}
//cout << sum << endl;
return (sum >= 5);
}
int main(int argc, char *argv[]) {
std::vector<vector<double> > vals {
{0, 0, 0, 0, 0}, // This has an energy of "0" -> does not count
{1, 1, 1, 1, 1}, // This has an energy of "5" -> push_back to vector[0]
{1, 1, 1, 1, 1}, // This has an energy of "5" -> push_back to vector[0]
{1, 1, 1, 1, 1}, // This has an energy of "5" -> push_back to vector[0]
{1, 2, 1, 1, 1}, //This has an energy of "5" -> push_back to vector[0]
{0, 0, 0, 0, 0}, // This has an energy of "0" -> does not count && start a new
// vector
{1, 2, 3, 4, 5}, // This has an energy of "55" -> push_back to vector[1]
{1, 2, 3, 4, 5}, // This has an energy of "55" -> push_back to vector[1]
{1, 2, 3, 4, 5}, // This has an energy of "55" -> push_back to vector[1]
{1, 2, 3, 4, 5} // This has an energy of "55" -> push_back to vector[1]
};
std::vector<vector<double> > clusters;
std::vector<vector<double> > tmp;
//std::for_each(vals.begin(), vals.end(), energy);
int j = 0;
for(unsigned i=0; (i < vals.size()); i++)
{
if(energy(vals[i]))
{
clusters.resize(j + 1);
clusters[j] = vals[i];
}else if(!energy(vals[i]) && energy(vals[i+1]))
{
j++;
}
}
for(unsigned i=0; (i < clusters.size()); i++)
{
for(unsigned j=0; (j < clusters[i].size()); j++)
{
cout << clusters[i][j] << ' ';
}
cout << endl;
}
}
应该发生什么
应该有2
向量的向量的元素,命名为clusters
每个包含以下值:
clusters[0] = {
1, 1, 1, 1, 1,
1, 1, 1, 1, 1,
1, 1, 1, 1, 1,
1, 2, 1, 1, 1
};
`clusters[1] = 1, 2, 3, 4, 5,
1, 2, 3, 4, 5,
1, 2, 3, 4, 5,
1, 2, 3, 4, 5}`
怎么了?
向量的向量似乎覆盖了插入其中的块。所以代替上面的,我只得到它发现的最后一个元素:
`cluster[0] = {1 2 1 1 1}
cluster[1] = {1 2 3 4 5}`
我正在考虑和尝试的是将每个“块”存储在包含足够能量的向量向量中,然后将所有这些值推入 a 中vector<double>
,然后将该向量插入到簇块中。
有没有另一种方法,一个更简单的解决这个问题的方法?