我有以下 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;
}
我在遍历 vector 时填写 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 是可选字段而不是重复字段时,上述代码才是正确的。我的问题是我缺少哪一行代码来使其成为重复字段?
最佳答案
不,你做对了。
这是我的 Protocol Buffer 的片段(为简洁起见,省略了详细信息):
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()
元素。
关于c++ - 如何在 C++ 中使用 Google 的 Protocol Buffer 添加重复字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1770707/