0

i also tried to use v.erase(v.begin()+j) but i still get the "debug assertion failed error box. this function suppose to erase the duplicate. Ex : {1,2,6,8,2,8} are the elements of the vector. this function has to make it {1,2,6,8}.

 void removeDup(vector<int>& v)
    {
    vector<int> x;
    int i,j,size;
    size=v.size();
    for(i=0;i<size;i++)
        {
         for(j=1;j<size;j++)
         {
          if(v[i]==v[j])
          {
            while(v.back()!=v[j])
            {
                x.push_back(v.back());
                v.pop_back();
            }
           v.pop_back();
           while(!x.empty())
           {
               v.push_back(x.back());
               x.pop_back();
           }
          }
         }
     }
    }

The problem occurs inside of the if(v[i]==v[j]) when i erase 2 while function and v.pop_back() program works without an error.

Can Özgen
  • 63
  • 1
  • 2
  • 8

1 Answers1

2

You are calculating the size of the vector v and using that as the loop iteration count limit. Unfortunately, you remove items from the v whenever you call pop_back inside the loop - this reduces the size of v but your loop is still going to attempt to access all the items that were in v when you calculated size at the start.

Therefore you end up accessing items that are outside the limits of the vector.

When working with vectors it is often more useful to work with iterators. Take a look at this similar SO question and answer as it might help you out Erasing elements from a vector

Community
  • 1
  • 1
mathematician1975
  • 21,161
  • 6
  • 59
  • 101
  • when i make it int size=v.size() size is stable? i can be wrong of course just i think that way – Can Özgen Nov 12 '15 at 21:21
  • @user3322385 An example: Say you have 10 items at the start. You remove one inside the loop so the new size is 9. You still try to access the 10th item but it is no longer there - this is an access violation outside the vector bounds – mathematician1975 Nov 12 '15 at 21:23
  • You can decrement `size` whenever you remove an element from the vector. – Barmar Nov 12 '15 at 21:23