Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

access to nth element of set

Tags:

c++

set

stl

There is a set visited. And I wanna check all its elements from 4-th to last. I'm trying to do something like that

int visited_pointer = 4;
for ( set<int>::iterator i_visited=visited.begin()+visited_pointer
    ; i_visited!=visited.end()
    ; i_visited++
)

and got errors with operator+.

How can I do that in the right way?

like image 863
ДМИТРИЙ МАЛИКОВ Avatar asked May 01 '11 11:05

ДМИТРИЙ МАЛИКОВ


People also ask

How do you access a particular element in a set?

You have to access the elements using an iterator. set<int> myset; myset. insert(100); int setint = *myset. begin();

Can we access set with index?

You can't access set using index but the above method would provide an "index" i if you want to copy the elements from set into an array, provided you have created an array of sufficient size before hand.

Does set have index in C++?

A set in c++ is an associative(STL) container used to store unique elements, and they are stored in a specific sorted order(increasing or decreasing). Elements of the set are unique, i.e., no duplicate values can be stored in the set because each value in the set is a key, and the set doesn't support indexing.


1 Answers

That usage of operator+ is only provided for random-access iterators. set iterators are bi-directional iterators.

But the function std::advance can be used to move any iterator a certain number of places:

#include <iterator>

//...

set<int>::iterator i_visited = visited.begin();
for ( std::advance(i_visited, visited_pointer)
    ; i_visited!=visited.end()
    ; ++i_visited
)
like image 64
aschepler Avatar answered Oct 15 '22 04:10

aschepler