Cannot copy vector

Hi all,

I've created a sieve of eratosthenes. The intial vector contains numbers 1- howmany and then replaced with 0 if not prime.

I want to remove the 0s. Instead of deleting vector elements I created a new vector to copy all non-0 elements but the program keeps crashing (when howmany is more than 100).

Any help would be great.

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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
#include <iostream>
#include <vector>
#include <fstream>

using namespace std;

int main()
{
    //initialise//
    int howmany=1000;

    vector <int> primes (howmany);

    for (int a=1;a<howmany;a++)
    {
        primes[a] = a;
    }

    //sieve


    for (int b=2;b<howmany;b++)
    {
        if (primes[b] == 0)
        {
            continue;
        }

        bool mult =true;
        int c=2;
            while (mult)
            {

                if ((c*b)>howmany)
                {
                    break;
                }


                primes[c*b]=0;

                c++;
            }

    }

//copy
vector <int> copied;

for ( int p=0;p<howmany;p++)
{
    if (primes[p]!=0)
    copied.push_back(primes[p]);
}



}
primes[c*b]=0; will fail if c*b == howmany.
Last edited on
Ah great thanks.
Topic archived. No new replies allowed.