我有以下简单程序:
#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/