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.
set::end() It returns an iterator pointing to past the last element of the set container.
Obviously if the iterator is advanced past the last element inside the loop the comparison in the for-loop statement will evaluate to false and the loop will happily continue into undefined behaviour.
Iterate over a set using an iterator. Iterate over a set in backward direction using reverse_iterator. Iterate over a set using range-based for loop. Iterate over a set using for_each loop.
Any element in list can be accessed using zero based index. If index is a negative number, count of index starts from end. As we want second to last element in list, use -2 as index.
To find the last element of a set what we can do is use an iterator that points to last of the of the set and then decrement the iterator to reach the last element as set.end() represent the iterator that points just outside the end of set.
auto it = s.end();
it--;
cout<<(*it)<<endl;
Just use *a.rbegin()
which points to the last element in the set
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With