C++ protobuf相关理解

发布时间 2023-12-07 00:27:43作者: CodeRabbit_joion

官网:https://protobuf.dev/reference/cpp/api-docs/

protobuf操作

protobuf中,repeated字段进行删除字段:
Protobuf v2
可以使用SwapElements(int index1, int index2),将要删除的字段移到最后,再用RemoveLast(),删除最后的元素。
Protobuf v3更新
可以通过iterator RepeatedField::erase(const_iterator position)可以在任意位置删除
 
message GuiChild
{
    optional string widgetName = 1;
    //..
}

message GuiLayout
{
    repeated ChildGuiElement children = 1;
    //..
}

typedef google_public::protobuf::RepeatedPtrField<GuiChild> RepeatedField;
typedef google_public::protobuf::Message Msg;

GuiLayout guiLayout; 
//Init children as necessary..

GuiChild child;
//Set child fileds..

DeleteElementsFromRepeatedField(*child, guiLayout->mutable_children());

void DeleteElementsFromRepeatedField(const Msg& msg, RepeatedField* repeatedField)
{
    for (RepeatedField::iterator it = repeatedField->begin(); it != repeatedField->end(); it++)
    {
        if (google_public::protobuf::util::MessageDifferencer::Equals(*it, msg))
        {
            repeatedField->erase(it);
            break;
        }
    }
}