Element at Index in a Std::Set

Element at index in a std::set?

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.

getting index of set element via iterator

Use STL distance, namely std::distance(set.begin(), mySetIterator)

Please note that:

Returns the number of elements between first and last. The behavior
is undefined
if last is not reachable from first by (possibly
repeatedly) incrementing first.

Remark : Complexity is linear;

However, if InputIt additionally meets the requirements of
LegacyRandomAccessIterator, complexity is constant.

Get element from arbitrary index in set

myset.begin() + 5; only works for random access iterators, which the iterators from std::set are not.

For input iterators, there's the function std::advance:

set<int>::iterator it = myset.begin();
std::advance(it, 5); // now it is advanced by five

In C++11, there's also std::next which is similar but doesn't change its argument:

auto it = std::next(myset.begin(), 5);

std::next requires a forward iterator. But since std::set<int>::iterator is a bidirectional iterator, both advance and next will work.

Loop in std::set by index

This feels like an error-prone cleanup strategy, but an improvement would probably require rewriting significantly more than what is provided in the question. (I suspect that shared and weak pointers could simplify things.) Since I lack enough information to suggest a better data structure:

For a set, it's easier to access the first element, *list_arc.begin(), than the last. (Not a huge difference, but still easier.)

How to set std::tuple element by index?

std::get returns a reference to the value. So you set the value like this:

std::get<0>(myTuple) = newValue;

This of course assumes that myTuple is non-const. You can even move items out of a tuple via std::move, by invoking it on the tuple:

auto movedTo = std::get<0>(std::move(myTuple));


Related Topics



Leave a reply



Submit