如何在 C++ 中使用 Google 的 Protocol Buffer 添加重复字段?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1770707/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 21:08:30  来源:igfitidea点击:

How do you add a repeated field using Google's Protocol Buffer in C++?

c++protocol-buffers

提问by aajkaltak

I have the below protocol buffer. Note that StockStatic is a repeated field.

我有以下协议缓冲区。请注意, 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;
}

I am filling out the StockStatic fields while iterating through a vector.

我在遍历向量时填写 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)
}

But the above code is right only if StockStatic was an optional field and not a repeated field. My questions is what line of code am i missing to make it a repeated field?

但是只有当 StockStatic 是可选字段而不是重复字段时,上面的代码才是正确的。我的问题是我缺少哪行代码才能使其成为重复字段?

回答by leegent

No, you're doing the right thing.

不,你在做正确的事。

Here's a snippet of my protocol buffer (details omitted for brevity):

这是我的协议缓冲区的片段(为简洁起见省略了详细信息):

message DemandSummary
{
    required uint32 solutionIndex     = 1;
    required uint32 demandID          = 2;
}
message ComputeResponse
{
    repeated DemandSummary solutionInfo  = 3;
}

...and the C++ to fill up ComputeResponse::solutionInfo:

...和 ​​C++ 来填充 ComputeResponse::solutionInfo:

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());
}

response.solutionInfonow contains demList.size()elements.

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

回答by VNarasimhaM

Another way of accomplishing the same thing:

完成同样事情的另一种方式:

message SearchResponse {
  message Result {
  required string url = 1;
  optional string title = 2;
  repeated string snippets = 3;
  }  
  repeated Result result = 1;
}