在&#34中调用std :: set函数时出现意外的评估结果;如果"声明

时间:2015-09-30 12:58:52

标签: c++ c++11

我发现了调用std :: set函数的行为在" if"声明做了我无法理解的事情,这是我的代码。

#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;
}

如果我输入:

3 2 1

输出结果为:

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

但是,如果我将插入移出&#34; if&#34;:

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");
    }

然后我可以得到预期的输出:

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

我还尝试使用以下代码进行测试:

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

输出是:

fun a encountered
fun b encountered

似乎订单是第一个代码中的预期。现在我很困惑。第一个代码出错的原因是什么?

2 个答案:

答案 0 :(得分:3)

这是不写复杂代码的好理由!

来自[intro.execution]:

  

除非另有说明,否则对单个操作符的操作数和单个表达式的子表达式的评估是不合理的。

当你写:

/sharedposts

您无法保证在(i=s.insert(t).first)==s.begin() 之前或之后调用begin()。如果它在 insert()之前被称为,那么显然插入的元素将不等于insert(),因为它们指向不同的东西。

只需在不同的行上写下你的作业和考试。空间不是溢价。 <更不用说了

begin()
除了定义明确的行为之外,

更容易阅读和理解。

答案 1 :(得分:1)

如果你改变这一行

changeset.errors[:email]

两个单独的陈述

if ((i=s.insert(t).first)==s.begin())

它会正常工作。问题是未定义auto result = s.insert(t); if (result.first == s.begin()) 或对insert的调用是先执行,所以begin先执行,然后begin迭代器将执行不比较平等。