我正在处理我的第一个代码,但我再次因新问题而受阻。
我在 vector A中有一堆值,我想执行以下while循环(以伪代码形式):
“创建一个变量 double SUM = 0 和一个变量 int count。
获取 vector 的前值,将其添加到SUM”
然后删除 vector 中的前面值
变量SUM应该充当电容器:当SUM优于给定常数u时,
SUM 等于 SUM - u
另一个 vector vectorB将每次SUM > u存储count的值
现在我只有一个包含所有值的 VectorA 以及将列表导出到 .txt 文件中的内容。
我想找到一种方法,将vectorA的前面的值放在一个局部变量中,将其添加到SUM中,然后删除这个前面的值。 那可能吗?有更好的方法吗?
代码如下:
#include <iostream>
#include <fstream>
#include <vector>
#include <iterator>
#include <cstdlib>
#include <string>
#include <sstream>
using namespace std;
// constant values
float Da=0.1; //densities
float Db=0.5;
float Dc=1;
double Dd=0.333333;
int l = 10; //width & height
int h = 10;
float u = 10; // UNIT
int main ()
{
// vectors
vector <double> VectorA;
vector <double> vectorB;
int I = 0; //itération pour la somme des valeurs du vecteur
double SUM = 0; //somme des éléments du vecteurA
float a = 0;
float b = 0; // Local variables
while (a<l+1, b<h+1){
//values for given a & b
double DL = Da-Da*(b/h)+Dc*(b/h);
double DR = Db-Db*(b/h)+Dd*(b/h);
double D = DL-DL*(a/l)+DR*(a/l);
//print
//cout<<D<<endl;
//store
VectorA.push_back (D);
// next pixel/unit & next line
a = a+u;
if (a>l) {
a = 0;
b = b+u;
}
}
// export values to .txt file
ofstream output_file("./step1.txt");
ostream_iterator<double> output_iterator(output_file, "\n");
copy(VectorA.begin(), VectorA.end(), output_iterator);
}
最佳答案
让我们把所有特定领域的内容去掉,让这个问题变得更简单,只讨论基本问题:
[How do I] put the front value of vectorA in a local variable to add it to SUM, and then erase this front value?
这是一个简单的方法:
vector <double> vectorA;
double SUM = 0.0;
// ...
while (!vectorA.empty())
{
const double curVal = vectorA.front(); // this strictly isn't necesarry. the compiler might optimize this away
SUM += curVal;
vectorA.erase (vectorA.begin());
}
现在让我们合并u
:
vector <double> vectorA;
double SUM = 0.0;
const double u = /* ??? */;
// ...
while (!vectorA.empty())
{
const int curVal = vectorA.front(); // this strictly isn't necesarry. the compiler might optimize this away
if (curVal > SUM)
{
SUM = curVal - u;
}
vectorA.erase (vectorA.begin());
}
我不太确定如何 count
行为,或者什么值被存储到 vectorB
,但作为一个疯狂的猜测,我将假设 count
每次 curVal > SUM
都会增加,以及所得的新值 count
插入到 vectorB
。那么让我们尝试实现它:
vector <double> vectorA;
double SUM = 0.0;
const double u = /* ??? */;
int count = 0;
vector <int> vectorB;
// ...
while (!vectorA.empty())
{
const int curVal = vectorA.front(); // this strictly isn't necesarry. the compiler might optimize this away
if (curVal > SUM)
{
SUM = curVal - u;
++count;
vectorB.push_back (count);
}
vectorA.erase (vectorA.begin());
}
上面有微优化的机会,但请记住 Knuth 的黄金法则:
Micro-optimization is the root of all evil.
构建软件时,最好的方法是首先选择正确的算法,并考虑到所需的效率(无论是空间效率还是时间效率),并以稳健、易于维护的方式构建它。然后在发布版本中分析您的程序,识别问题热点,并仅在必要时对代码的这些部分进行微优化。如果您一开始就选择了正确的算法,并将其编写得很好,您通常会发现不需要进行微优化。
关于c++ - 迭代:变量和 vector 前面的和,导出到另一个 vector ,删除 vector 前面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17571190/