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.
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.
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.
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()
.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With