zoukankan      html  css  js  c++  java
  • protobuf--repeated get set

    普通字段
    package test_namespace;
    
    message FatherMsg {
        repeated string father = 1;    
    }
    #include <stdio.h>
    #include <iostream>
    #include <string>
    
    #include "test.pb.h"
    
    using namespace std;
    
    int main()
    {
        // 方式1
        /*
        test_namespace::FatherMsg father_msg;
    
        string* str1 = father_msg.add_father();
        *str1 = string("hello");
    
        string* str2 = father_msg.add_father();
        *str2 = string("world");
    
        for (int i = 0; i < father_msg.father_size(); i++)
        {
            cout << father_msg.father(i) << endl; 
        }
        */
        // 方式2 (建议)
        test_namespace::FatherMsg father_msg;
        father_msg.add_father("hello");
        father_msg.add_father("world");
    
        for (int i = 0; i < father_msg.father_size(); i++)
        {
            cout << father_msg.father(i) << endl; 
        }
        
        return 0;
    }
    message字段

    package test_namespace; message ChildMsg { optional
    string child = 1; } message FatherMsg { repeated ChildMsg child_msg = 1; }
    #include <stdio.h>
    #include <iostream>
    #include <string>
    
    #include "test.pb.h"
    
    using namespace std;
    
    int main()
    {
        // 方式1(建议)
        test_namespace::FatherMsg father_msg; 
        test_namespace::ChildMsg* ch;  // 如果ChildMsg嵌套在FatherMsg中, 则为test_namespace::FatherMsg::ChildMsg* ch;
    
        ch = father_msg.add_child_msg();
        ch->set_child("hello");
        ch = father_msg.add_child_msg();
        ch->set_child("world");
    
        /*
        // 方式2 如果需要设置child_msg多个成员, 则不适用
        test_namespace::FatherMsg father_msg; 
    
        father_msg.add_child_msg()->set_child("hello");
        father_msg.add_child_msg()->set_child("world");
    
    
        // 方式3
        test_namespace::FatherMsg father_msg; 
    
        father_msg.add_child_msg();
        father_msg.mutable_child_msg(0)->set_child("hello");
        father_msg.add_child_msg();
        father_msg.mutable_child_msg(1)->set_child("world");
       
        */ 
    
        // output
        for (int i = 0; i < father_msg.child_msg_size(); i++)
        {
            cout << father_msg.child_msg(i).child() << endl; 
        }
    
        return 0;
    }
  • 相关阅读:
    2021NUAA暑假集训 Day3 题解
    2021NUAA暑假集训 Day2 题解
    2021NUAA暑期模拟赛部分题解
    CodeForces 1038D Slime
    UVA 11149 Power of Matrix
    UVA 10655 Contemplation! Algebra
    UVA 10689 Yet another Number Sequence
    HDU 4549 M斐波那契数列
    HDU 4990 Reading comprehension
    CodeForces 450B Jzzhu and Sequences
  • 原文地址:https://www.cnblogs.com/helloweworld/p/4211480.html
Copyright © 2011-2022 走看看