24

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.

Sachin Singh
  • 7,107
  • 6
  • 40
  • 80

3 Answers3

17

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().

kabanus
  • 24,623
  • 6
  • 41
  • 74
4

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.

Hamza
  • 41
  • 2
1

A set has an iterator so you can loop over it like this How to iterate std::set?

return_moves.begin() returns an iterator to the "first" element (in laymen terms a better pointer to the "first" element). So

return_moves.begin()->size()

should be used instead.

I am using "first" element because that is the smallest element of the set according to the sorting criterion (it might be the first inserted but probably would be something else).

Max Play
  • 3,717
  • 1
  • 22
  • 39
kyticka
  • 604
  • 8
  • 19