Повторное поле буфера Google Protocol Buffer С++
У меня есть следующий буфер протокола. Обратите внимание, что 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 был необязательным полем, а не повторным полем. Мои вопросы - какая строка кода мне не хватает, чтобы сделать ее повторяющейся?
Ответы
Ответ 1
Нет, вы поступаете правильно.
Вот фрагмент моего PB (подробности для краткости):
message DemandSummary
{
required uint32 solutionIndex = 1;
required uint32 demandID = 2;
}
message ComputeResponse
{
repeated DemandSummary solutionInfo = 3;
}
... и С++ для заполнения 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().
Ответ 2
Еще один способ выполнить одно и то же:
message SearchResponse {
message Result {
required string url = 1;
optional string title = 2;
repeated string snippets = 3;
}
repeated Result result = 1;
}