-3

I think I am not using the iterator properly but I don't see what's wrong with my code:

#include <iostream>
#include <set>
#include <ctime>
#include <cstdlib>
#include <sstream>

int main(){
  stringstream s;

  set<int> a, b, c;
  set<set<int> > d;

  set<set<int> >::iterator pos;

  srand(time(0));

  d.insert(a);
  d.insert(b);
  d.insert(c);

  for (pos = d.begin(); pos != d.end(); pos++){
      for (int i=0;i<10;i++){
          (*pos).insert(genInt(1,10));
      }
      s << "\nSet: " << endl << *pos;
  }
  s << endl;
}

I'm trying to initialize the three sets with random integers, while being part of another set.

The compilation error is in (*pos).insert(genInt(1,10)):

error: no matching function for call to ‘std::set<int>::insert(int) const’

genInt(1,10) returns a random integer between 1 and 10.

int genInt(int min, int max){
int tam = max - min + 1;
return ( (rand() % tam) + min);
}
calm-tedesco
  • 256
  • 5
  • 12

1 Answers1

2

You can't modify a set's elements. The error is correct that there is no const insert method.

error: no matching function for call to ‘std::set::insert(int) const

pos is an iterator on a set and can only provides a const reference to the element it refers to. As such, only const member functions can be called with that reference. A std::set stores it's elements in an ordered way that allows it to quickly find them. To change one of it's elements would upset that ordering. You will have to construct your sub-sets completely before inserting them into the greater set of sets.

François Andrieux
  • 28,148
  • 6
  • 56
  • 87