Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get element from arbitrary index in set

Tags:

c++

stl

I have a set of type set<int> and I want to get an iterator to someplace that is not the beginning.

I am doing the following:

set<int>::iterator it = myset.begin() + 5;

I am curious why this is not working and what is the correct way to get an iterator to where I want it.

like image 825
Programmer Avatar asked Jan 18 '12 08:01

Programmer


People also ask

How do you find the elements of a set?

You can't access set elements by index. You have to access the elements using an iterator. set<int> myset; myset. insert(100); int setint = *myset.

Does set have index in C++?

The boolean value denotes if index is found the set or not. The integer value contains the integer stored at index in the set. If the boolean value is set true, which indicates index to be a valid index, print the integer value stored in the pair.

How do you find the position of an element in a set C++?

set find() function in C++ STL Return Value: The function returns an iterator which points to the element which is searched in the set container. If the element is not found, then the iterator points to the position just after the last element in the set.


1 Answers

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.

like image 190
R. Martinho Fernandes Avatar answered Oct 01 '22 17:10

R. Martinho Fernandes