-1

I am currently learning C++ / making a simple movie database. I use classes and I have a method Delete Movie. Unfortunately, when I try to delete object Movie from a vector database, there's this error.

        for (size_t num {}; num < database.size(); ++num) 
            if ((database.at(num)).getname() == name) {
                database.erase(num); // <--- error here
                return true;
            }

Can someone hopefully tell me, what am I making wrong? If you need more information, I can send the whole file.

Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
  • 1
    Because [erase](https://en.cppreference.com/w/cpp/container/vector/erase) accepts `iterator` as an argument, not `size_t`. For example `database.begin() + i` – pptaszni Jul 30 '20 at 11:14
  • dupe of [How do I erase an element from std::vector<> by index?](https://stackoverflow.com/questions/875103/how-do-i-erase-an-element-from-stdvector-by-index) – underscore_d Jul 30 '20 at 11:16
  • 1
    Please don't make more work for other people by vandalizing your posts. By posting on the Stack Exchange network, you've granted a non-revocable right, under the [CC BY-SA 4.0 license](https://creativecommons.org/licenses/by-sa/4.0/), for Stack Exchange to distribute that content (i.e. regardless of your future choices). By Stack Exchange policy, the non-vandalized version of the post is the one which is distributed. Thus, any vandalism will be reverted. If you want to know more about deleting a post please see: [How does deleting work?](https://meta.stackexchange.com/q/5221) – Tomerikoo Jun 03 '21 at 10:49

1 Answers1

2

erase accepts iterator as said pptaszni

Replace your for code by this:

auto it = std::remove_if(database.begin(), database.end(), [&name](const Movie& item) -> bool { return item.getname() == name; });
database.erase(it, database.end());

Or change just 1 line (database.erase(num)) like this:

database.erase(database.begin() + num);
Ihor Drachuk
  • 1,265
  • 7
  • 17