2009-11-20 92 views
11

我有下面的协议缓冲区。请注意,StockStatic是一个重复的字段。谷歌协议缓冲区重复字段C++

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是一个可选字段,而不是重复栏。我的问题是我错过了哪些代码,使它成为重复的字段?

+0

只是好奇,当你重复这个问题时,你面对的问题到底是什么? – VNarasimhaM 2009-11-20 14:59:53

回答

13

不,你做正确的事情。

这是我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()元素。

+0

谢谢..我刚刚意识到调用response-> add_solutioninfo()----添加了超过1个元素..谢谢! – aajkaltak 2009-11-20 15:23:52

0

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

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

for **重复的字符串片段**什么是cpp代码? – 2018-02-07 16:04:10