How does this code find a non-positive value?
#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");
}
The output is:
Is 4 non-positive?
Is 3 non-positive?
Is 1 non-positive?
Is -3 non-positive?
Yes it is!
So how does the “second < 0” string check for a non-positive value?
Some hints for parsing
--p--->second. It is evaluated as--((p--)->second). (Thanks to @AProgrammer for fixing my blatant error!)pis a pointer or iterator.p--decrementsp, but returns its previous value as an rvalue(p--)->secondaccesses that value’s membersecond.--((p--)->second)decrements that value (i.e. the mapped value) and returns the new, decremented valueThat new value is compared against
0Notes:
The
p--takes care of iterating over the container. Note that the loop doesn’t otherwise have any explicit change ofp.The outer
--makes0count as a negative number. As a side effect, the loop decrements every value in the map.The second use of
iis somewhat redundant. You could have writtenp->secondinside the loop rather thansecond[++i], since you already have an iterator. In fact,second[++i]necessitates a whole tree search.The code is equivalent to: