0

I have this map where keys are strings and values are vectors of Product type (structs containing and int "code" variable and some other variables). Given a code, I want to remove all occurrences of vector elements where that code is present, and I need to do this for all map elements. This is what I'm trying and my program crashes:

void removeByCode(map<string, vector<Product>> &products, int code){
    for (auto productlist: products){
        for (auto i=productlist.second.begin(); i != productlist.second.end(); i++){
            if ((*i).code==code)
                i = productlist.second.erase(i);
        }
    }
}

This is one use case where it crashes (assume this is what the map pairs look like):

a: [code:1; code:2]

b: [code:1]

c: [code:1; code:2]

Code to be erased: 2

PS: I need to use erase (not remove or other methods)

  • Your second loop should be replaced with the erase and remove idiom. See the dupe on how that works – NathanOliver Oct 17 '16 at 13:59
  • 1
    For the inner loop you might want to look at [Erasing elements from a vector](http://stackoverflow.com/questions/347441/erasing-elements-from-a-vector?rq=1). Right now `i++` skips the next element after the erased one. Or, worse, increments the end iterator if you erased the last element. – Bo Persson Oct 17 '16 at 14:01
  • "PS: I need to use erase (not remove or other methods)" - why? Is this an assignment for educational purposes? If not, please explain why "remove" is forbidden. – Martin Bonner supports Monica Oct 17 '16 at 14:01
  • Is there no way to do it without using remove? I'm not worried about complexity here, just need to use erase effectively. – Vanessa Larralde Oct 17 '16 at 14:02
  • @BoPersson: And because the erased one is sometimes the last one, the OP can advance off the en of the vector. – Martin Bonner supports Monica Oct 17 '16 at 14:03
  • @Martin - Yes, that would explain the crash and not just a wrong result. – Bo Persson Oct 17 '16 at 14:05
  • No, it's not an assignment, just for learning purposes. I didn't realize erase would skip the next element, so I tweaked the inner loop into this (but now it doesn't erase a single thing, it just doesn't crash): `auto i = productlist.second.begin(); while (i != productlist.second.end()){ if ((*i).code==code) i = productlist.second.erase(i); else i++; }` – Vanessa Larralde Oct 17 '16 at 14:12

0 Answers0