I came across the following code here, which is from the C++ implementation of Dijkstra algorithm using an adjacency matrix.
//read in edges keeping only the minimum
for(int i=0; i<E; i++) {
int v1,v2,tmp;
fin >> v1; fin >> v2;
fin >> tmp;
adjmat[v1][v2]<?=tmp; // <?= sets left to min(left,right)
adjmat[v2][v1]<?=tmp;
}
Pay attention to the last two lines, which apply operator <?=
. As being commented, the following line
adjmat[v1][v2]<?=tmp; // <?= sets left to min(left,right)
will set left
to min(left,right)
.
I never see this operator before. I tried the code in VS, it can not compile. What is it? How can it set left
to be min(left,right)
?
It is equivalent to:
In general:
a OP ?= b;
<=>a = (a OP b)? a : b;
A little example (compiled using MingW2.95 and C-Free IDE on Windows) showing what @Kerrek SB said: the GCC extension evalute operands only once, which it's nice
It is an old GCC extension; it does what it says in the comment (it's the compound assignment form of the "minimum" operator). This is not standard C++.
The difference between
a = a < b ? a : b
anda <?= b
is that the latter only evaluates each operand once.In modern standard C++, I believe you could write an "assign the minimum" algorithm like this:
This should be the body of a macro which has the effect of
a <?= b
, anda
andb
are arbitrary expressions, potentially with side effects. Or you could wrap it into a template: