c++ - 如何在 C++ 中使用 Google 的 Protocol Buffer 添加重复字段?

标签 c++ protocol-buffers

我有以下 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/

相关文章:

c++ - C 和 C++ 静态初始化之间的区别

c++ - 为什么要将类放在实现文件中?

protocol-buffers - 为什么ProtoBuf在第一次调用时这么慢但是在内部循环中却非常快?

asp.net - Google Protocol Buffers 或类似的 .net/javascript

spring-boot - 使用 JpaRepository 将 protobuf 直接保存为实体

unix - 是否有用于检查 Protocol Buffer 的权威 *nix 命令行工具?

c++ - 有符号/无符号比较和 -Wall

c++ - OnKillFocus 未被调用

c++ - 为什么我的程序返回 5?

java - 用于处理 protobuf 的 Eclipse 插件