-1

So I have to write my own method.

I did the following:

vector<float> remove(vector<float>& sortedVector, float input)
{

    for (vector<float>::iterator it = sortedVector.begin() ; it != sortedVector.end(); ++it)
    {
        if(input == *it)
        {
            sortedVector.erase(it);
        }
    }

    return sortedVector;
}

However compiler breaks at for loop. Where did I go wrong? I need to return the modified vector after the given value of the user is removed from the vector.

Output of the error

Bayazid
  • 9
  • 2
  • instead of making your own function just use the [erase and remove idiom](https://en.wikipedia.org/wiki/Erase%E2%80%93remove_idiom) – NathanOliver Feb 29 '16 at 21:13
  • @NathanOliver Because he says "i have to write my own method", this is probably for a course or something. – Colin Basnett Feb 29 '16 at 21:14
  • 1
    The compiler breaks? What compiler are you using that suffers an _internal error_ with something this simple? – Weak to Enuma Elish Feb 29 '16 at 21:15
  • 2
    After `erase(it)` the iterator is invalid and `++it` is undefined. – Bo Persson Feb 29 '16 at 21:16
  • Returning a copy of a vector passed into the function by reference? That cannot be right. – Christian Hackl Feb 29 '16 at 21:18
  • @ChristianHackl fairly new to both vector and by reference. I need to remove an element user wants to remove then update the original vector. – Bayazid Feb 29 '16 at 21:27
  • @Bayazid Seriously, if you showed up at a job interview with your own function to erase from a vector, it would not be looked upon highly by the interviewer. Who is teaching your class? – PaulMcKenzie Feb 29 '16 at 21:38

1 Answers1

0

Why make your own function? You can simply do this:

vector.erase(std::remove(vector.begin(), vector.end(), item_to_delete ), vector.end()); 
Marinos K
  • 1,595
  • 11
  • 32
  • I'm required to write my own function. – Bayazid Feb 29 '16 at 21:26
  • 1
    @Bayazid Your requirements didn't state you had to write a `for` loop, only that you had to write a function. That function could have inside of it the call to `erase / remove`. – PaulMcKenzie Feb 29 '16 at 21:44
  • exactly.. you can wrap my code in you function and that's it.. and if you prefer something more verbose - check the actual implementation of these algorithms to devise your own version. – Marinos K Feb 29 '16 at 21:46
  • *"I have to write my own method"* is synonymous for *"cannot use a library"*. Providing a solution that wraps a library call in a function does not meet that requirement. You cannot possibly be **this** dense. Suggesting to study the implementation (likely incomprehensible, even to somewhat experienced developers) is like saying RTFM. -1 for the undue arrogance alone. – IInspectable Mar 01 '16 at 02:04
  • "I have to write my own method" is NOT synonymous for "cannot use a library". – Marinos K Mar 01 '16 at 05:37