使用 std::set 的 .begin() 和 .end() 函数会产生意想不到的结果

Using std::set's .begin() and .end() function produces unexpected results

本文关键字:意想不到 结果 函数 end begin std 使用 set      更新时间:2023-10-16

我有以下简单的程序:

#include <iostream>
#include <set>
using namespace std;
int main()
{
    unsigned int qwer = 6132;
    unsigned int ty = 3512;
    unsigned int vv = 4331;
    unsigned int gg = 1337;
    set<unsigned int> asdf = {};
    asdf.insert(qwer);
    asdf.insert(ty);
    asdf.insert(vv);
    asdf.insert(gg);
    cout << "&asdf.begin() = " << &asdf.begin();
    unsigned int setint = *asdf.begin();
    cout << "nsetint = " << setint;
    setint = *asdf.end();
    cout << "nsetint = " << setint;
    cout << "n&asdf.end() = " << &asdf.end();
    return 0;
}

它产生以下输出:

&asdf.begin() = 0x22fe08
setint = 1337
setint = 4
&asdf.end() = 0x22fe08

为什么asdf.begin()asdf.end()的地址匹配?我假设他们会有不同的地址指向不同的值?尽管它们的地址确实匹配,但指向的值不匹配!这是为什么呢?

编辑:还有为什么setint = asdf.end((似乎将setint的值设置为集合中的元素数量而不是集合中的最后一个值?(我假设应该是6132吧?

你有很多未定义的行为。

&asdf.begin()
&asdf.end()

您正在获取 prvalue 的地址。 &只能应用于左值和限定 ids(有名称的事物(

*asdf.end()

迭代器end不可取消引用。它指向"一过即止"的立场。