mercredi 30 septembre 2015

Unexpected evaluate result when calling std::set functions in "if" statement

I found the behavior of calling std::set function in the "if" statement does something I can't understand, here is my code.

#include<set>
#include<iostream>
#include<cstdio>
using namespace std;
set<int>s;int t;
set<int>::iterator i;
int main()
{
    while (cin>>t) {
        if ((i=s.insert(t).first)==s.begin())
/*Expected: 
insert the new element, 
get the iterator of the new inserted element and save it into i,
and compare it to the begin of the set to see if it is the smallest. */
            puts("the new int is the smallest");
        else puts("the new int is not the smallest");
    }
    return 0;
}

If I input:

3 2 1

The output would be:

the new int is not the smallest
the new int is not the smallest
the new int is not the smallest

However, if I move the insert out of the "if":

while (cin>>t) {
        (i=s.insert(t).first);
        if (i==s.begin())
            puts("the new int is the smallest");
        else puts("the new int is not the smallest");
    }

Then I can get the expected output:

the new int is the smallest
the new int is the smallest
the new int is the smallest

I also tried to test using the following code:

int a() {
    puts("fun a encountered");
    return 1;
}
int b() {
    puts("fun b encountered");
    return 1;
}
int main()
{
    int x;
    if ((x=a())==b());
}

And the output is:

fun a encountered
fun b encountered

Seems like the order is what was expected in the first code. Now I am very confused. what is the reason for the first code went wrong?

Aucun commentaire:

Enregistrer un commentaire