"until(-- p ---> second < 0)"如何循环直到找到非正值

How does "until(-- p ---> second < 0)" loop until a non-positive value in found

本文关键字:循环 何循环 until gt lt second      更新时间:2023-10-16

此代码如何查找非正值?

#include <map>
#include <cstdio>
#define until(cond) while(!(cond))
using namespace std;
int main() {
  // initialization
  map<int,int> second;
  int i=10;
  int testme[10]={4,3,1,-3,7,-10,33,8,4,14};
  while (i --> 0) second[i]=testme[i];
  // find the first non-positive value in second
  map<int,int>::reverse_iterator p = --second.rend();
  do {
    printf("Is %d non-positive?n",second[++i]);
  } until(-- p --->   second < 0);
    // "second < 0" to check if the value in second is non-positive
  printf("Yes it is!n");
}

输出为:

Is 4 non-positive?
Is 3 non-positive?
Is 1 non-positive?
Is -3 non-positive?
Yes it is!

那么,"second<0"字符串如何检查非正值呢?

解析--p--->second的一些提示。评价为--((p--)->second)。(感谢@AProgrammer修复了我的明显错误!)

  • p是一个指针或迭代器。

  • p--递减p,但返回其值作为右值

  • (p--)->second访问该值的成员second

  • --((p--)->second)递减该值(即映射值)并返回新的递减值

  • 将该新值与0 进行比较

注:

  • p--负责对容器进行迭代。请注意,循环在其他方面没有p的任何显式更改。

  • 外部CCD_ 12使CCD_ 13计数为负数。作为副作用,循环会递减贴图中的每个值。

  • i的第二次使用有些多余。您可以在循环中编写p->second,而不是second[++i],因为您已经有了迭代器。事实上,second[++i]需要进行整树搜索。

该代码相当于:

do { /* ... */
    auto q = p;
    --p;
    --(q->second);
} until (q->second < 0);

实际上,它检查值是否不是正的,也不是负的:http://liveworkspace.org/code/587a9554a2b0b8f830179518133c2274

正如Kerrek所说的

do { /*...*/ }
until(-- p --->   second < 0);

相当于:

do { /*...*/ }
until(--((p--)->second) < 0);

相当于:

do { /*...*/ } 
while(((p--)->second)-- > 0);

所以,如果值是0,它也会断开。