Problems with stl set, and Random numbers

Im making a program to generate random sets of Polinoms (which are stored using dynamic memory on the Polinom class). However, i'm getting stuck on a forever loop in this method (i seems to always be equal to 1)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
set<Polinom> Random::generate(const unsigned& n) const{



   srand((unsigned)time(0));
   set<Polinom> aux;
   set<Polinom>::iterator it;
   unsigned size, i =0;
   //We create an ammount "n" of Polinoms
   while (i < n ){
      size = unsigned((9*rand()/(RAND_MAX)) +1);
      int *p = new int[size];
      for (unsigned j = 0; j<size; j++){
         p[j] = (int (10*rand()/(RAND_MAX)));
      }
      Polinom poli(p,size);
      // To create a polinom, we give it a randomly
      // generated dynamic vector, and its length
      delete [] p;
      it = aux.find(poli);
      if (it ==  aux.end()) {
         aux.insert(poli);
         i++;
      }
      // it only inserts the polinom if it isn't already on the set
   }
   return aux;
}
Last edited on
So if it != aux.end() i is never incremented.
i is incremented, but only one time.
it = aux.end() in case aux.find(p) couldn't find the polynom p in the set<Polynom> called aux.

Im thinking this error could be related to the fact im running it on a Kubuntu virtual machine under windows.
I'm gonna give it a try under windows

EDIT: Under windows i have the same error. Infinite loop with i = 1.
However, random polynoms are generated properly (they're always different). In kubuntu they were always blank polynoms.

so.. the error could be here

1
2
3
4
5
      it = aux.find(poli);
      if (it ==  aux.end()) {
         aux.insert(poli);
         i++;
      }


Im thinking that the error could be related to multiset, and its the default compare operator (which is <, and has been already overloaded in polynom).

EDIT 2: Btw, "i" is the count of inserted polynoms.
Last edited on
What does Polinom's operator< look like?

You probably want to move the srand() call to main and call it only once.

Also, set::insert returns a std::pair<iterator, bool> where the bool is set to true if the element was
unique and therefore inserted, or false otherwise. So you could rewrite lines 20-24 as:

1
2
if( aux.insert( poli ).second )
    ++i;


And in fact since i is just counting the number of elements inserted and you start with any empty set,
you could eliminate i altogether and use set::size() [less efficient, but you won't notice a difference
for small sets].

1
2
3
4
while( aux.size() < n ) {
   // ...
  aux.insert( poli );   // size() will not change if insert failed because of duplicate
}

Topic archived. No new replies allowed.