erase last vector element ( crash)

I want to erase the last element from the vector.
I then do vec.erase(vec.end() - 1) . How ever, the program crashes at this level.

here is my code.

1
2
3
4
5
6
7
8
9
10
11
while(next)
    {
        for(int i = 0; i < prime.size(); i++)
            sum += prime.at(i);

        if(sum < max && isPrime(sum))
            next = false;
        else
           prime.erase(prime.end() - 1); //still crash if i change 1 to any other positive number 
                                //still crash if i use prime.erase(prime.begin() + x) ,x = any positive number
    }


Any ideas?
Last edited on
Are you sure the vector is not empty when you do this?
NO. Its not empty. Here is the complete code

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
#include <iostream>
#include <vector>

using namespace std;

bool isPrime(int);
ostream &operator<<(ostream &, vector <int> &);

int main()
{
    vector <int> prime;
    const int max = 100;
    int sum = 0;

    bool next = true;

    int i = 0;
    while(i < max)
    {
        if(isPrime(i))
            prime.push_back(i);
        i++;
    }
    while(next)
    {
        for(int i = 0; i < prime.size(); i++)
            sum += prime.at(i);
        if(sum < max && isPrime(sum))
            next = false;
        else
           prime.erase(prime.end() - 1);
    }
    cout<<prime;

    cin.ignore();
    return 0;
}
bool isPrime(int a)
{
    for(int i = 2; i <= a/2; i++)
        if(a%i == 0)
            return false;
    return true;
}
ostream &operator<<(ostream &out, vector <int> &vec)
{
    for(int i = 0; i < vec.size(); i++)
        out<<vec.at(i)<<"  ";
    return out;
}
yes, it is empty. Set a conditional breakpoint and you may observe it, after that is undefined behaviour.


In line 28 you ask for `sum' to be less than `max', that's impossible. Perhaps you forgot to reset `sum', or the condition is another one, ¿what are you trying to solve?

Also, you consider 0 and 1 to be primes (they are not)


By the way, you may use http://www.cplusplus.com/reference/vector/vector/pop_back/
Last edited on
Your vector is indeed empty at the point where the program crashes.

It looks like you forgot to reinitialize sum. Try setting sum to zero at the beginning of the while(next) loop.
Resetting sum fixed the issue. Thanks guys.
But i dont understand how sum determined whether the vector is empty or not.
Because sum was not being reset, your condition if(sum < max && isPrime(sum)) was always false after some point. This caused your else condition to then always be hit, thus infinitely trying to remove the last element.
Thank you @shacktar, I now understand the reason for the crash.
Topic archived. No new replies allowed.