Can map::find and iterator::second be used in one condition - c++11

I have such a piece of code:
std::map<int, int> mp;
// do something
auto itor = mp.find(some_value);
if (itor != mp.end() && itor->second == some_other_value) {
// do something
}
I'm worrying about which expression would be evaluated first, itor != mp.end() or itor->second == some_other_value?
If the second one is evaluated firstly (because of some compiler-optimization maybe?), it might get an undefined behavior because itor == mp.end() may be true.
Should I worry about this issue so that I have to code like this:
if (itor != mp.end) {
if (itor->second == some_other_value) {
// do something
}
}

No worries; your code is fine.
If the first condition of if (a && b) is false, then the second condition is not evaluated.
Look up "short-circuit evaluation"
Wikipedia has some info.

Logical And - && - expression is evaluated left to right so itor != mp.end() will be evaluated initially. Moreover, it returns true only if both expressions return true, hence if the first one is false the second one is not checked.
so the first case should work.

Related

How to alter Boolean value from true to false and vice-versa

I have a requirement in Go of altering the bool value and store it.
I am receiving value == true but I need to alter it and store the altered value.
I can think of only storing the alerted to a var and pass it in the next statement.
Eg psuedo code:
chnagevalue := false
if value == false {
changevalue == true
}
what's the best way to do it in Go? Is there any pre-defined way to do it?
Use the logical NOT operator ! to change true to false and vice versa:
changedValue := !value
There's a short answer, written somewhere else :-)
Yours is almost good too:
changedValue := false
if !value {
changedValue == true
}
An if statement is always about something being true.
so in the above it reads : if a value equals false is true then {}.
of course your mind reads it the short way :
if a value equals false then {}.
the switch of course works the best:
changedValue := !changedValue
BTW: I would never use a fieldname like "changedValue" because...
every variable is a value of some kind, so there is no need of writing that.
"changed" should be enough.
or, when it is a boolean like this , even better:
"isChanged" or "hasChanged"

Does DM-script have lazy evaluation?

I am wondering if there is no lazy evaluation in dm-script?
I have the following code fragment that checks, if a TagGroup is valid. It throwns an error telling me the TagGroup is not defined so the TagGroupCountTags() function cannot be exeucted on this TagGroup. But that is the purpose of this fragment, checking if the TagGroup and the index are valid.
I tried to debug the code. The first statement tg.TagGroupIsValid() returns false, 0 <= index of course too. Why is the tg.TagGroupCountTags() still being executed? I can't beleave there is no lazy evaluation.
number index = -1; // of course this is not set to -1 in my original code, this is just for demonstration
TagGroup tg;
clearResults();
result(tg.TagGroupIsValid() + "\n"); // resturns 0
result((0 <= index) + "\n"); // returns 0
if(tg.TagGroupIsValid() && 0 <= index && index < tg.TagGroupCountTags()){
result("Valid.");
}
else{
result("Invalid.");
}
Yes, conditions in DM-Script are always completely evaluated (no lazy evaluation), so you have to put the If-clauses in a nested way. This is also true if you're using a tertiary operator (?).

Using find_if with vector object

this code always returns false
I tried to pass lambda parameter by reference and I had the same result
any tip please
vector<int> v1;
v1.push_back(1);
v1.push_back(2);
v1.push_back(3);
v1.push_back(5);
for (int x : v1)
{
auto it = find_if(v1.begin(), v1.end(), [x](int y){ return x == y; });
if (it != v1.end())
return false;
return true;
}
To check for duplicates (not remove them, just check for them) then you can do something like this:
Get the first value, and check for it in the rest of the container. You should not check the first element again because that's the element we are checking currently.
If a duplicate is not found then go on to the second element, and check from the third element forward. WE don't need to check the first element because that was done in the previous step.
Then continue like that for all elements.
If you find a duplicate then stop the searching and return true. If none are found then continue until the end, and then return false.
This can be done easily using iterators:
// Outer loop, current element to check
for (auto const i = v1.begin(); i != v1.end(); ++i)
{
// Inner loop, the element to check against
for (auto const j = i + 1; j != v1.end(); ++j)
{
if (*i == *j)
return true; // Duplicate found
}
}
// No duplicates found
return false;
The above code shows the principle, you could of course use std::find_if instead of the inner loop. The important thing is to start looking at the next element. All the previous have already been checked, and you should not compare the current value with itself.
Look at your condition in the if. What you meant it to do and what it actually does?
From using for it looks like you want it to go over all the container. Can you find a case where the body of the loop doesn't return immediately on the first iteration?

Coding styles in conditional expression of some programming languages

It's a bit confusing to me about what is the difference between these condition expressions below:
if( 1 == a) {
//something
}
and
if( a == 1 ) {
//something
}
I saw the above one in some scripts I have downloaded and I wonder what's the difference between them.
The former has been coined a Yoda Condition.
Using if(constant == variable) instead of if(variable == constant), like if(1 == a). Because it's like saying "if blue is the sky" or "if tall is the man".
The constant == variable syntax is often used to avoid mistyping == as =. It is, of course, often used without understanding also when you have constant == function_call_retuning_nothing_modifiable.
Other than that there's no difference, unless you have some weird operator override.
Many programming languages allow assignments like a = 1 to be used as expressions, making the following code syntactically valid (given that integers can be used in conditionals, such as in C or many scripting languages):
if (a = 1) {
// something
}
This is rarely desired, and can lead to unexpected behavior. If 1 == a is used, then this mistake cannot occur because 1 = a is not valid.
Well, I am not sure about the trick. Generally, we could say the equal sign is commutative. So, a = b implies b = a. However, when you have == or === this doesn't work in certain cases, for example when on the right side you have a range: 5 === (1..10) vs. (1..10) === 5.

Binary tree recursive problem

I found this problem and I am not very sure if my approach approach is right:
"A binary tree can be encoded using
two functions l and r such that for a
node n, l(n) gives the left child of
n(or nil if there is none) and r(n)
gives the right child(or nil if there
is none).Let Test(l,r,x) be a simple
recursive algorithm for taking a
binary tree encoded by the l and r
functions together with the root node
x for the binary tree, and returns
"yes" if no node in the tree has
exactly one child. Give the pseudocode
for this algorithm."
I tried this:
test(l,r,x)
if((l(x)!=null && r(x)!=null) || (l(x)==null && r(x)==null))
return "yes"
else return "no"
if(test(l,r,l(x))=="yes") test (l,r,l(x)) else return "no"
if(test(l,r,r(x))=="yes") test (l,r,r(x)) else return "no"
return "yes"
Is it correct? If l and r are functions, why are they passed as normal parameters when the function is called?
Thank you in advance for your answers!
You have three basic conditions: both children are null, one child is null, or neither child is null. I'd test them in that order as well (because it simplifies the logic a bit):
if l(x) == null && r(x) == null
return true;
if l(x) == null || r(x) == null // only need inclusive OR, due to previous test.
return false;
return test(l, r, l(x)) && test(l, r, r(x))
As far as passing l and r as parameters goes, it all depends: some languages (e.g., functional languages) allow you to pass a function as a parameter. Others (e.g., C, C++, etc.) have you pass a pointer to a function instead -- but it's pretty much irrelevant. A few won't let you pass anything like a function, in which case you'd have to hardwire it in. In this case, you're not really gaining much (anything?) by passing l and r as parameters anyway. Passing a function as a parameter is useful primarily when/if the receiving function doesn't know what function it's going to receive a priori (which it does here).
the first thing you do is either return yes or no, so the last part is unreachable.
I would change it so that if you have one child, you return no, otherwise you return yes or no depending on if your children meet the criteria.
test(l,r,x)
if((l(x)!=null && r(x)==null) || (l(x)==null && r(x)!=null))
return "no"
if(l(x) == null && r(x) == null)
return "yes"
return test(l,r,l(x)) && test(l,r,r(x))
I don't think this is correct. The problem I see is in the first step:
if((l(x)!=null && r(x)!=null) || (l(x)==null && r(x)==null))
return "yes"
else return "no"
The problem is that you cannot determine the 'yes' for the entire tree at the first step. What you have to do is break it up into components:
if this node has both children
return the result of test(l,r,l(x)) && (test(l,r,r(x))
if this node has no children
return true
if this node has 1 child
return false
as per your last question ("If l and r are functions, why are they passed as normal parameters when the function is called?"), the answer is that they don't have to be passed as parameters. That's just the notation they chose when they said "A binary tree can be encoded using two functions l and r [...]"

Resources