Sudhanshu Gupta
Sudhanshu Gupta

Reputation: 2315

Segmentation fault while erasing vector

while(!v1.empty() || !v2.empty())
{
    int k=0;        
    if(v1[k] < v2[k])
        v1.erase(v1.begin());
    else
        v2.erase(v2.begin());
    cout<<v1[0];
}

this is my code here i want to remove the elements till one of them is empty(vectors are sorted) , like if

v1 contains 2,3,5,8

v2 contains 3,4,7

then according to me it should give me 8 but its giving segmentation fault

Upvotes: 0

Views: 582

Answers (4)

Ade YU
Ade YU

Reputation: 2362

while(!v1.empty() && !v2.empty())
{
    int k=0;        
    if(v1[k] < v2[k])
        v1.erase(v1.begin());
    else
        v2.erase(v2.begin());
}
if (!v1.empty()) {
    cout << v1[0];
} else if (!v2.empty()) {
    cout << v2[0];
}

Upvotes: 2

iammilind
iammilind

Reputation: 69988

Below condition:

if(v1[k] < v2[k])

This condition doesn't check, if a vector is already empty or not. If one of the vectors gets emptied then you are accessing an forbidden location (either v1[0] or v2[0]). So your condition should be like:

while(!(v1.empty() || v2.empty()))

Upvotes: 0

maverik
maverik

Reputation: 5586

Use &&:

while( !v1.empty() && !v2.empty())
{
    ...
}

The second fall is that you use v1[0] after erase. If erase deletes last element of the vector v1 then v1[0] leads to undefined behavior.

if(v1[0] < v2[0])
    v1.erase(v1.begin());
else
    v2.erase(v2.begin());
cout << v1[0];

Upvotes: 2

Michael Chinen
Michael Chinen

Reputation: 18697

Use && instead of ||:

while( !v1.empty() && !v2.empty())

Without that you are entering the while loop when one of the vectors is empty, and subsequently trying to access an element that isn't there.

Upvotes: 5

Related Questions