Google Protocol Buffer重复了字段C ++

时间:2009-11-20 14:18:25

标签: 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;
}

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

但是,只有当StockStatic是可选字段而不是重复字段时,上述代码才是正确的。我的问题是我缺少什么代码来使它成为一个重复的字段?

3 个答案:

答案 0 :(得分:17)

不,你做的是正确的事。

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

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

...和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.solutionInfo现在包含demList.size()元素。

答案 1 :(得分:0)

这里是 c++ 示例代码,但可能效率不高:

message MyArray
{
    repeated uint64 my_data = 1;
}
//Copy
std::array<unsigned long long, 5> test={1,1,2,3,5};
mynamespace::MyArray pbvar;
auto *dst_ptr = keys.my_data();
google::protobuf::RepeatedField<google::protobuf::uint64> field{test.begin(), test.end()};
dst_ptr->CopyFrom(field);

//Output
for (auto it : pbvar.my_data())
    std::cout<<it<<" ";
std::cout<<std::endl;

答案 2 :(得分:0)

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

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