0
点赞
收藏
分享

微信扫一扫

c++使用proto3的map

软件共享软件 2022-03-25 阅读 106
java后端

Introduction:

自proto3开始, proto2和proto3就可以支持map.
##官方文档中有如下声明:##

Added support for map fields (implemented in both proto2 and proto3).
Map fields can be declared using the following syntax:

>message Foo {
  map<string, string> values = 1;
}

The data of a map field is stored in memory as an unordered map and
can be accessed through generated accessors.

proto3 map源码:

template<typename Key, typename T> {
class Map {
  // Member types
  typedef Key key_type;
  typedef T mapped_type;
  typedef MapPair< Key, T > value_type;

  // Iterators
  iterator begin();
  const_iterator begin() const;
  const_iterator cbegin() const;
  iterator end();
  const_iterator end() const;
  const_iterator cend() const;
  // Capacity
  int size() const;
  bool empty() const;

  // Element access
  T& operator[](const Key& key);
  const T& at(const Key& key) const;
  T& at(const Key& key);

  // Lookup
  int count(const Key& key) const;
  const_iterator find(const Key& key) const;
  iterator find(const Key& key);

  // Modifiers
  pair<iterator, bool> insert(const value_type& value);
  template<class InputIt>
  void insert(InputIt first, InputIt last);
  size_type erase(const Key& Key);
  iterator erase(const_iterator pos);
  iterator erase(const_iterator first, const_iterator last);
  void clear();

  // Copy
  Map(const Map& other);
  Map& operator=(const Map& other);
}

map的赋值方式:

1.简单的赋值方式:

最简单的赋值方式就是用C++的普通Map语法, 如下第二行:

std::unique_ptr<ProtoName> my_enclosing_proto(new ProtoName);
(*my_enclosing_proto->mutable_weight())[my_key] = my_value;

2.有效的赋值方式:

pair<iterator, bool> insert(const value_type& value)会隐式地调用value_type实例的深拷贝, 最有效的插入新值方式是:

T& operator[](const Key& key): map[new_key] = new_mapped;

std::map与google::protobuf::Map的相互转换:

google::protobuf::Map转换成std::map:

google::protobuf::Map 支持std::map和std::unordered_map的API, 如果你不想直接使用google::protobuf::Map, 可以如下方式将google::protobuf::Map转换成标准库的Map

std::map<int32, int32> standard_map(message.weight().begin(),
                                    message.weight().end());

注意:这会深拷贝整个Map

std::map转换成google::protobuf::Map:

You can also construct a google::protobuf::Map from a standard map as follows:

当然, 你也可以通过标准库中的Map构造一个google::protobuf::Map, 如下所示:

google::protobuf::Map<int32, int32> weight(standard_map.begin(), standard_map.end());
举报

相关推荐

0 条评论