I have the following code in 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;
}
Why is it always printing "3" instead of the greatest element in the set? Replacing cout << *a.end();
with cout << *--a.end();
works fine.
end()
is not pointing to the last element, it is pointing one past it. C++ ranges are closed at the front, open at the back:[begin, end)
.std::set::end
reference have a nice figure illustrating it.