如何在C++中遍历谷歌原型地图?

How to iterate through a google protobuf map in C++?

本文关键字:谷歌 原型 地图 遍历 C++      更新时间:2023-10-16

我的地图采用以下形式:

const google::protobuf::Map<string, nrtprofile::RedisNewsMetric> map=redisNewsMessage.ig();

我应该如何遍历映射以获取所有键和相应的值?

您以与std::unordered_map完全相同的方式遍历google::protobuf::Map

for (auto & pair : map)
{
doSomethingWithKey(pair.first);
doSomethingWithValue(pair.second);
}

如果您有 C++17 编译器,则可以使用结构化绑定进一步拆分该编译器

for (auto & [key, value] : map)
{
doSomethingWithKey(key);
doSomethingWithValue(value);
}

来自文档

google::p rotobuf::map是一种特殊的容器类型,用于协议缓冲区中存储映射字段。从下面的界面可以看出,它使用了 std::map 和 std::unordered_map 方法的常用子集

google::p rotobuf::map支持与std::map和std::unordered_map相同的迭代器API。如果您不想直接使用 google::p rotobuf::map,您可以通过执行以下操作将 google::p rotobuf::Map 转换为标准地图:

因此,以下示例代码中显示的两种方法中的任何一种都应该有效:

int main ()
{
std::map<char,int> mymap;
mymap['b'] = 100;
mymap['a'] = 200;
mymap['c'] = 300;
// show content:
for (std::map<char,int>::iterator it=mymap.begin(); it!=mymap.end(); ++it)
std::cout << it->first << " => " << it->second << 'n';
for (auto& x : mymap)
std::cout << x.first << " => " << x.second << 'n';
return 0;
}

能够使用 protobuf Map 进行结构化绑定for

for (auto & [key, value] : map) {
}

您需要包含以下代码来告诉编译器执行此操作:

namespace std {
template<typename TK, typename TV>
class tuple_size<google::protobuf::MapPair<TK,TV>> : public std::integral_constant<size_t, 2> { };
template<size_t I, typename TK, typename TV> 
struct tuple_element< I, google::protobuf::MapPair<TK, TV>> { };
template<typename TK, typename TV> struct tuple_element<0, google::protobuf::MapPair<TK, TV>> { using type = TK; };
template<typename TK, typename TV> struct tuple_element<1, google::protobuf::MapPair<TK, TV>> { using type = TV; };
template<int I, typename TK, typename TV>
auto get(const google::protobuf::MapPair<TK, TV>& x) {
if constexpr (I == 0) return x.first;
if constexpr (I == 1) return x.second;
}
}