【发布时间】:2016-12-23 13:34:09
【问题描述】:
我在 C++ 中有以下代码
#include <iostream>
#include <set>
using namespace std;
int main()
{
set<int> a;
int n;
for(int i=0;i<3;i++){
cin>>n;
a.insert(n);
}
cout << *a.end();
return 0;
}
为什么总是打印“3”而不是集合中的最大元素?将 cout << *a.end(); 替换为 cout << *--a.end(); 可以正常工作。
【问题讨论】:
-
end()是 not 指向最后一个元素,它指向 一个过去它。 C++ 范围在前面关闭,在后面打开:[begin, end)。 -
This
std::set::endreference 有一个很好的插图来说明它。 -
我还以为后面也关了。谢谢!