0

I have a protobuf::mutable pointer,

auto del_list = message_my.mutable_del_list()

I want to delete its repeated_field.h which times below 10, so I use the function below:

for (auto del_item = del_list->begin(); del_item != del_list->end();) {
    if (del_item->times() < 10) {
       del_list->erase(del_item++);
       continue;
    }
    del_item++;
}

but the program core dump because of it. Why?

I think I have noticed the iterator erase problem, why?

  • What guarantees does the class give you for its iterators after `erase` is called? Because if this is actually a `std::vector` or a similar, you cannot use `.erase(del_item++)` the way you do. – j6t Aug 26 '22 at 11:40
  • so how to solve this problem ? how to delete its repeated_field ? – Brian Liew Aug 26 '22 at 11:46
  • Idiomatically, you write `del_item = del_list->erase(del_item);` provided that the container class follows the usual convention that `erase` returns the iterator to the element after the one that was deleted. – j6t Aug 26 '22 at 12:05
  • [`RepeatedPtrField`](https://developers.google.com/protocol-buffers/docs/reference/cpp/google.protobuf.repeated_field#RepeatedPtrField) is not a `std::vector`, but it looks similar enough to one that the usual [erase-remove idiom](https://stackoverflow.com/questions/39019806/using-erase-remove-if-idiom) should work. – Igor Tandetnik Aug 26 '22 at 14:22

0 Answers0