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

标签 c++ stl set

我有以下简单程序:

#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()

您正在获取纯右值的地址。 & 只能应用于左值和qualified-id(有名称的东西)

*asdf.end()

end 迭代器不可解引用。它指向“最后一个”位置。

关于c++ - 使用 std::set 的 .begin() 和 .end() 函数会产生意想不到的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56391175/

相关文章:

python - 删除集合列表的重复项

javafx - 如何使用 Set 作为 TableView 的基础

c++ - 可以realloc Array,那为什么要用指针呢?

c++ - 由于分配,c++中的指针算术

c++ - 转义字符串中的反斜杠?

c++ - 如何通过键和值比较两个映射并将差异映射存储在 C++ 的结果映射中?我们有它的任何 STL api 吗?

list - TCL中有类似std::set的数据结构吗?

c++ - 随机生成可被N整除的数字的最佳算法

c++ - 为什么在离开作用域时指向字符串文字的外部指针会丢失? (C++)

c++ - 从 STL 容器中删除元素时是否调用析构函数?