How to delete arbitrary objects in repeated field? (protobuf)

后端 未结 5 1218
广开言路
广开言路 2021-02-18 17:51

I have some entries in the repeated field in my proto. Now I want delete some of them. How can I accomplish this? There is a function to delete the last element, but I want to d

5条回答
  •  南笙
    南笙 (楼主)
    2021-02-18 18:36

    Although there's no straight-forward method you still can do this (for custom message using reflection). Code below removes count repeated field items starting from row index.

    void RemoveFromRepeatedField(
        const google::protobuf::Reflection *reflection,
        const google::protobuf::FieldDescriptor *field,
        google::protobuf::Message *message,
        int row,
        int count)
    {
        int size = reflection->FieldSize(*message, field);
        // shift all remaining elements
        for (int i = row; i < size - count; ++i)
            reflection->SwapElements(message, field, i, i + count);
        // delete elements from reflection
        for (int i = 0; i < count; ++i)
            reflection->RemoveLast(message, field);
    }
    

提交回复
热议问题