protobuf-c++之-数组使用

这篇博客详细介绍了Protocol Buffers(Protobuf)中数组的操作,包括查看数组长度、清空数组、获取指定位置元素及插入数组元素的方法。通过示例展示了如何在`Activity`消息类型中操作`children`数组,为protobuf使用者提供了清晰的操作指南。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

目录

1、proto文件

2、pb.h源码

3、数组的基本操作

3.1、返回数组长度,看源码

3.2、清空数组,看源码

3.3、返回具体位置内容,看源码

3.4、插入数组


1、proto文件

// 组件类型数据
message Activity{
    // 子组件列表
    repeated Activity children = 1;
    // 组件的输入/输出参数 属性列表没有使用map,让属性列表可以出现同名,但是数值不同的的参数
    repeated ActivityProperty properties=2;
}

2、pb.h源码

首先翻看pb.h源码,找到children成员的操作方法:

//返回数组长度
inline int Activity::children_size() const {
  return _internal_children_size();
}
//清空数组
inline void Activity::clear_children() {
  children_.Clear();
}
//在具体的位置插入数组
inline ::workflow::Activity* Activity::mutable_children(int index) {
  // @@protoc_insertion_point(field_mutable:workflow.Activity.children)
  return children_.Mutable(index);
}
inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::workflow::Activity >*
Activity::mutable_children() {
  // @@protoc_insertion_point(field_mutable_list:workflow.Activity.children)
  return &children_;
}
//返回具体位置数组
inline const ::workflow::Activity& Activity::_internal_children(int index) const {
  return children_.Get(index);
}
//返回具体位置数组
inline const ::workflow::Activity& Activity::children(int index) const {
  // @@protoc_insertion_point(field_get:workflow.Activity.children)
  return _internal_children(index);
}
//插入数组
inline ::workflow::Activity* Activity::_internal_add_children() {
  return children_.Add();
}
//插入数组
inline ::workflow::Activity* Activity::add_children() {
  ::workflow::Activity* _add = _internal_add_children();
  // @@protoc_insertion_point(field_add:workflow.Activity.children)
  return _add;
}

3、数组的基本操作

3.1、返回数组长度,看源码

3.2、清空数组,看源码

3.3、返回具体位置内容,看源码

3.4、插入数组

Activity accumulate;
Activity printer;
Activity whileDo;

Activity sequence;
//protobuf 数组的添加
*(sequence.add_children()) = accumulate;
*(sequence.add_children()) = printer;
*(sequence.add_children()) = whileDo;

 总之:protocbuf对数组已经提供了非常丰富的操作方法,翻看源码就可以知晓所有我们需要的操作。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值