如何比较两个连续的迭代步骤?在C++

how can i compare two consecutive iteration steps? in C++

本文关键字:迭代 C++ 两个 何比较 比较 连续      更新时间:2023-10-16

我构建了一个循环调用的程序。每次值 T 发生变化时,我想比较上一个周期的值 T 和 T,并为每个周期执行此操作。

int T = externalsrc; //some external source
int prevT; //cannot do it because in the first cycle it will have no value when used in comparison
int prevT = 0; //cannot do it, because in every cycle prevT will be zero for my comparison
int comparison = prevT - T;
prevT = T;

那我怎样才能正确地做到这一点呢?我也试过这个,但这里仍然没有声明 T:

int T;
int prevT;
if (prevT != T)
  prevT = 0;
else
  prevT = externalsrc;
int comparison = prevT - T;
prevT = T;

使用你的第一个答案,但将prevT声明为 static 并将 init 初始化为 0:

while (condition) {
    int T = externalsrc; //some external source
    static int prevT = 0; // declaring static means that it will only be set to 0 once
    int comparison = prevT - T;
    prevT = T;
}

。这样,在每次后续迭代中,将忽略prevT的初始化,并保留上次迭代的值。

你可以保留一个布尔变量来告诉你它是否是第一次。

像这样的事情:

bool first_fime = true;
// ...
if (first_time)
{
    // Do something with T only
    previousT = T;
    // It's no longer the first time
    first_time = false;
}
else
{
    // Do something with both T and previousT
}

您可以将 prevT 定义为函数中的static

你的代码将是这样的

int T = externalsrc; //some external source
int prevT; //cannot do it because in the first cycle it will have no value when used in comparison
static int prevT = 0; //The first time it is called it will start with pr
int comparison = prevT - T;
prevT = T;
struct compare
{
    compare() { prev = 0; }
    int operator() (int t)
    {
        int cmp;
        cmp = prev - t;
        prev = t;
        return cmp;
    }
private:
    int prev;
};