Sieve of Eratosthenes using STL set

I am trying to write a program that takes in a upper bound(int) and then inserts all values up to that bound in a set and then use the sieve of Eratosthenes to remove all non prime integers. I am not sure what I am doing wrong.

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
29
30
31
32
33
34
35
36
37
38
39
40
  int main()
{
int n;
set<int> s;
cout << "Enter an Upper Bound: ";
cin >> n;

sieve(s , n);

        return 0;
}

void print_primes(const set<int>& s)
{
 int newLine = 1; //counter for new line after 16 values have been printed
        for(int i = 0; i<*s.rbegin() ; i++)
        {
                cout << setw(ITEM_W) << s[i] << " ";
                if(newLine == NUM_ITEMS)
                {
                        cout << endl;
                        newLine = 0;
                }
                newLine++;
        }
        
void sieve( set<int>& s, int n)
{
        for(int i =1; i<=n; i++)
                s.insert(i);

        for(int m = 2; m<s.*rbegin(); m++)
        {
               for (int k = m;  k<=n; k++)
                s.erase(m*k);
        }

        print_primes(s);
}
Last edited on
Perhaps the dollar sign on line 13 might start explaining your problems. I think you are looking for the reference operator "&"

Also line 32, the "int <" operator is not defined for s.end() which is an iterator. Either use an iterator or use *s.rbegin(). I put the "*" sign to dereference the pointer so that you can access the value
Last edited on
Thank you so much I needed an extra set of eyes and that fixed 99% of my errors... now I am experiencing problems with my stdout statement. the compiler doesn't like the square brackets in s[i]

heres the error:

prog3.cc: In function ‘void print_primes(const std::set<int>&)’:
prog3.cc:18:44: error: no match for ‘operator[]’ in ‘s[i]’
First notice that your for-loop on line 29 starts the loop at value "1" and the one on line 16 starts at 0.

As for your error with the square brackets, use iterators instead like this:

typedef set<int>::iterator s_iter;

1
2
3
4
5
6
7
8
9
10
11
12
13
14
void print_primes(const set<int>& s)
{
	int newLine = 1; //counter for new line after 16 values have been printed
	for(s_iter i = s.begin(); i != s.end(); i++)
	{
		cout << *i << " ";
		if(newLine == NUM_ITEMS)
		{
			cout << endl;
			newLine = 0;
		}
		newLine++;
	}
}


Alternatively, use *s.find(i) as opposed to s[i]
Last edited on
Thanks the iterator fixed it... as for the looping structures, I started line 29 at 1 because I was inserting values from 1 to n, and n is a user defined upper bound. Thanks again you were a tremendous help
Topic archived. No new replies allowed.