在开始和结束条件下切换for循环
Switch the for loop basis on start and end condition
我有一个下面的代码,其中我从传递给getUser
方法的timestamp
获得start
值。并且我从current timestamp
中得到了以毫秒为单位的end
值。
start
的最小值可以是0
,而end
的最大值可以是13
。因此,如果start
总是小于end
,我下面的for循环将正常工作。
bool getUser(uint64_t timestamp) {
uint64_t start = (timestamp / (60 * 60 * 1000 * 24)) % 14;
struct timeval tp;
gettimeofday(&tp, NULL);
uint64_t ms = tp.tv_sec * 1000 + tp.tv_usec / 1000; //get current timestamp in milliseconds
uint64_t end = (ms / (60 * 60 * 1000 * 24)) % 14;
for (uint64_t i = start; i<=end; i++) {
}
}
但在某个时刻,start
也可能大于end
。也就是说,假设start
的值是9
,end
的值是2
,那么我上面的for循环就不起作用了,因为在这种情况下,我想从9 to 2
迭代我的for循环,它将是i = 9, 10, 11, 12, 13, 0, 1, 2
。
如何确保start
小于end
且start
大于end
,则我的上述for循环在这两种情况下都能正常工作。。
如果开始小于结束,我上面的for循环可以很好地工作,但它不适用于大于end
的start
非常简单,因此可以理解。当然还有很大的改进空间。
if(start > end)
end += 14;
for (uint64_t i = start; i<=end; i++) {
// operate on i%14
}
为什么不使用while循环:
do{
//code here
++start;
if(start==14)
start=0;
} while(start!=end);
相关文章:
- 如何在C++中从两个单独的for循环中添加两个数组
- 为什么我的for循环不能正确获取argv
- 在基于范围的for循环中使用结构化绑定声明
- 通过for循环使用用户输入填充列表
- 使用for循环检查数组中的重复项
- 在for循环中使用auto vs decltype(vec.size())来处理字符串的向量
- 为什么 const std::p air<K,V>& 在 std::map 上基于范围的 for 循环不起作用?
- 正在使用for循环创建QScatterSerie
- Python中的for循环与C++有何不同
- 在更改for循环的第三部分后,未使用for循环结果
- 在 for 循环中查找问题时遇到困难
- 嵌套for循环C++的问题(初学者)
- 如何用for循环在c++中生成单词三角形
- 如何在for循环中包含两个索引值的测试条件
- 带有多个独立参数的C++For循环
- 为什么我的程序在for循环中k=0时返回垃圾值
- 如何通过替换顺序代码的while循环来添加OpenMP for循环
- C++-For循环未执行
- 基于范围的 for 循环:迭代使用一个元素扩展的向量
- C++ 无法在字符数组中使用 for 循环打印字母模式