Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ iterator to last element of a set

Tags:

c++

iterator

set

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.

like image 792
Abdullah Shahriar Avatar asked Dec 23 '16 13:12

Abdullah Shahriar


People also ask

How do you find the iterator to the last element of a set?

set::end() It returns an iterator pointing to past the last element of the set container.

What happens if you increment the iterator past the end?

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.

How do I loop through set STL?

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.

How do you get the second last element of a set?

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.


2 Answers

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;

like image 137
parad0x Avatar answered Oct 21 '22 04:10

parad0x


Just use *a.rbegin() which points to the last element in the set

like image 33
user10517710 Avatar answered Oct 21 '22 05:10

user10517710