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.
Because
a.end()
is one past the end of your vector. It doesn't hold any valid data, it's a marker for the end of your vector. As in:EDIT: (thanks to Nathan) dereferencing
a.end()
yields the dreaded undefined behaviour. Anything could have happened: get a3
, get the last element in the set, could even have canceled X-mas!!!Undefined behaviour. In C++ iterator terminology, "end" does not mean the same thing as "last element".
Consider a reverse iterator:
*a.rbegin()
.Keep in mind that both
begin()
andrbegin()
only return dereferencable iterators if the container is not empty. For empty containers,begin() == end()
andrbegin() == rend()
.Just use
*a.rbegin()
which points to the last element in the set