Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get just first element of set in c++

Tags:

c++

set

I am new to c++, I have declared set of sets:

std::set< std::set<int> > return_moves;

and also pushed some values in it. I want to access the first element of this set so that I can count a number of elements in that inner set. I am trying to get it by

return_moves.begin().size()

I am getting this error:

set_diff.cpp: In function ‘int main()’:
set_diff.cpp:62:47: error: ‘std::set<std::set<int> >::iterator {aka struct std::_Rb_tree_const_iterator<std::set<int> >}’ has no member named ‘size’

Please help me to rectify my syntax.

like image 353
Sachin Singh Avatar asked Nov 18 '17 09:11

Sachin Singh


People also ask

How do you return the first element of a set?

begin() function is used to return an iterator pointing to the first element of the set container. begin() function returns a bidirectional iterator to the first element of the container. Syntax: setname.

How do you find the top element of a set?

rend() methods Approach: Elements in a set are stored in sorted order. So the minimum element of the set will reside in the first element and the maximum element in the last element. Therefore, this first and last element can be fetched with the help of set. rend() and set.


2 Answers

Elaborating on Ed's comment, a set in C++ is by default weakly ordered, so there is some guarantee to the iteration ordering, but as a mathematical concept there is no "order" in a set, and hence implementations do not usually allow obtaining a "first" element.

If you want just to obtain any element, without iterating you can use

auto someElementIterator = myset.begin()

which will return an iterator to some element. To "pop" it you can follow it with

myset.erase(someElementIterator)

and you can get the element using *someElementIterator.

Regarding your error:

An iterator is in some some sense like a pointer, you need -> not . To access the element size (rather than the iterator size, which doesn't exist). so:

someElementIterator->size()

and not someElementIterator.size().

like image 191
kabanus Avatar answered Oct 19 '22 11:10

kabanus


I'm late sorry, i just passed and found the solution for next developpers.
To get the first element of the std::set you could just use :

std::set< std::set<int> > return_moves;
auto oneMove = *(return_moves.begin()); // will return the first set<int>

oneMove.size(); // will return the size of the first set<int>

Because return_moves.begin() return the iterator of the first element of the set, and by adding the * we will recive the value of the first element.

like image 45
Hamza Avatar answered Oct 19 '22 10:10

Hamza