30

我有以下协议缓冲区。请注意,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 是可选字段而不是重复字段时,上面的代码才是正确的。我的问题是我缺少哪一行代码以使其成为重复字段?

4

3 回答 3

43

不,你做对了。

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

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

...以及填充 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());
}

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

于 2009-11-20T15:15:49.310 回答
0

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

message SearchResponse {
  message Result {
  required string url = 1;
  optional string title = 2;
  repeated string snippets = 3;
  }  
  repeated Result result = 1;
}
于 2009-11-20T15:11:34.857 回答
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;
于 2021-01-10T08:07:44.500 回答