Element at index in a std::set?

Solution 1:

It doesn't cause a crash, it just doesn't compile. set doesn't have access by index.

You can get the nth element like this:

std::set<int>::iterator it = my_set.begin();
std::advance(it, n);
int x = *it;

Assuming my_set.size() > n, of course. You should be aware that this operation takes time approximately proportional to n. In C++11 there's a nicer way of writing it:

int x = *std::next(my_set.begin(), n);

Again, you have to know that n is in bounds first.

Solution 2:

A usual implementation of std::set is to use binary search trees, notably self-balancing binary search trees such as red-black trees

They don't give you constant time access to the n-th element. However, you seems to want the first. So try in C++11:

auto it = my_set.begin();
int first=0;
if (it != my_set.end()) first = *it;

Solution 3:

Try this you will be able to use set in another way namely ordered_set

This is very much used in CP

Hope this is diff from all and will help you/someone!

#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;
#define ordered_set tree<int,null_type,less<int>,rb_tree_tag,tree_order_statistics_node_update>

Now you can use

order_of_key (k) : Number of items strictly smaller than k .
find_by_order(k) : K-th element in a set (counting from zero). //This is what you need 


https://www.geeksforgeeks.org/ordered-set-gnu-c-pbds/