2009-11-20 127 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