从 Google Protocol buffer 中的重复字符串 ( list ) 中删除一个随机值

Delete a random value from repeated string ( list ) in Google Protocol buffer

我想从重复字段中删除一个项目

假设我们有一个消息定义:

message foo {
repeated string temp1 ; 
repeated string temp2 ; 
}

我想从某个随机索引处的 temp1 中删除项目;

据我所知,我可以通过交换最后一个元素并使用 RemoveLast 来删除; 但我不知道如何使用它。对 c++ 中的代码快照有帮助吗?

这是一个 reason 为什么 protocol buffer 中没有 Remove()

I didn't want to provide a Remove(int) because it would be O(n). Version 1 of protocol buffers had such a function, and we frequently saw people writing loops like:

 for (int i = 0; i < field.size(); i++) {
  if (ShouldFilter(field[i])) {
    field.Remove(i);
    --i;
  }
}

This loop is O(n^2), which is bad, but it's hard to tell that it is O(n^2). The idea behind only providing RemoveLast() is to force you to either do something clever (like swapping the element with the last element first, as the documentation suggests) or write your own loop which makes the time complexity of your code obvious.

这里有两个选项:

  • 将列表末尾的项目复制到space之前被要删除的项目占用,然后调用RemoveLast().

  • 通过使用iterator erase(const_iterator position),但是你应该从begin()开始,然后检查是否应该删除这个迭代器的值。