如何比较两个连续的迭代步骤?在C++
how can i compare two consecutive iteration steps? in C++
我构建了一个循环调用的程序。每次值 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;
};
相关文章:
- 使用std::multimap迭代器创建std::list
- 来自 std::list 的迭代器 .end() 按预期返回"0xcdcdcdcdcdcdcdcd"但 .begin()
- C++中带有List类的迭代器Segfault
- 迭代时从向量和内存中删除对象
- 如何在c++迭代器类型中包装std::chrono
- 带过滤器的现代迭代c++集合
- 在c++中检查长方体是否尽可能快地重叠(无迭代)
- C++矢量迭代
- 集合上的输出迭代器:assign和increment迭代器
- Boost Spirit,获取迭代器内部语义动作
- 擦除while循环中迭代的元素
- 实现一个在集合上迭代的模板函数
- 对于set上的循环-获取next元素迭代器
- 在向量内的向量上迭代
- 为什么output_editor Concept不需要output_e迭代器标记
- TSP递归解的迭代形式
- c++17文件系统::recursive_directory迭代器()在mac上没有给出这样的目录,但在windows上
- 使用迭代器时如何访问对象在向量中的位置?
- std::vector::迭代器是否可以合法地作为指针
- 跟随整数索引列表的自定义类迭代器