Google Protocol Buffer重复了字段C++

aaj*_*tak 19 c++ protocol-buffers

我有以下协议缓冲区.请注意,StockStatic是一个重复的字段.

message ServiceResponse
{
    enum Type
    {
        REQUEST_FAILED = 1;
        STOCK_STATIC_SNAPSHOT = 2;
    }

    message StockStaticSnapshot
    {
        repeated StockStatic stock_static = 1;
    }
    required Type type = 1;
    optional StockStaticSnapshot stock_static_snapshot = 2;
}

message StockStatic
{
    optional string sector      = 1;
    optional string subsector   = 2;
}
Run Code Online (Sandbox Code Playgroud)

我在迭代向量时填写StockStatic字段.

ServiceResponse.set_type(ServiceResponse_Type_STOCK_STATIC_SNAPSHOT);

ServiceResponse_StockStaticSnapshot stockStaticSnapshot;

for (vector<stockStaticInfo>::iterator it = m_staticStocks.begin(); it!= m_staticStocks.end(); ++it)
{
    StockStatic* pStockStaticEntity = stockStaticSnapshot.add_stock_static();

    SetStockStaticProtoFields(*it, pStockStaticEntity); // sets sector and subsector field to pStockStaticEntity by reading the fields using (*it)
}
Run Code Online (Sandbox Code Playgroud)

但是,只有当StockStatic是可选字段而不是重复字段时,上述代码才是正确的.我的问题是我错过了哪些代码来使它成为一个重复的字段?

小智 20

不,你正在做正确的事.

这是我的PB的片段(为简洁而省略的细节):

message DemandSummary
{
    required uint32 solutionIndex     = 1;
    required uint32 demandID          = 2;
}
message ComputeResponse
{
    repeated DemandSummary solutionInfo  = 3;
}
Run Code Online (Sandbox Code Playgroud)

...以及填充ComputeResponse :: solutionInfo的C++:

ComputeResponse response;

for ( int i = 0; i < demList.size(); ++i ) {

    DemandSummary* summary = response->add_solutioninfo();
    summary->set_solutionindex(solutionID);
    summary->set_demandid(demList[i].toUInt());
}
Run Code Online (Sandbox Code Playgroud)

response.solutionInfo现在包含demList.size()元素.

  • `DemandSummary* summary = response-&gt;add_solutioninfo();` 应更改为 `DemandSummary* summary = response.add_solutioninfo();` 出于某种原因,stackoverflow 表示建议的编辑队列已满 (2认同)