自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.
The easiest way to add data is to use normal map syntax, for example:
最简单的赋值方式就是用C++的普通Map语法, 如下第二行:
std::unique_ptr<ProtoName> my_enclosing_proto(new ProtoName); (*my_enclosing_proto->mutable_weight())[my_key] = my_value;pair<iterator, bool> insert(const value_type& value) will implicitly cause a deep copy of the value_type instance. The most efficient way to insert a new value into a google::protobuf::Map is as follows:
pair<iterator, bool> insert(const value_type& value)会隐式地调用value_type实例的深拷贝, 最有效的插入新值方式是:
T& operator[](const Key& key): map[new_key] = new_mapped;Using google::protobuf::Map with standard maps google::protobuf::Map supports the same iterator API as std::map and std::unordered_map. If you don’t want to use google::protobuf::Map directly, you can convert a google::protobuf::Map to a standard map by doing the following:
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());Note that this will make a deep copy of the entire map.
注意:这会深拷贝整个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());