如何在C++中遍历谷歌原型地图?
How to iterate through a google protobuf map in C++?
我的地图采用以下形式:
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;
}
}
相关文章:
- 奇怪的(对我来说)返回声明 - 在谷歌上找不到任何关于它的信息
- 谷歌测试中的期望值存储在哪里
- 谷歌模拟和覆盖关键字
- 如何使用ESP8266向谷歌主页发送命令
- 更正 CMakeList.txt 用于谷歌测试的文件?
- 如何将GTest与CMake一起使用?遵循谷歌指南时的链接问题
- 在没有 API 的情况下使用谷歌翻译文本
- 重载运算符<<采用谷歌 C++ 风格
- 如何在谷歌模拟中匹配 C 样式数组
- 如何让谷歌测试正常运行。测试总是失败。(它不会编译)
- 为什么我收到来自谷歌的错误请求?
- 如何使用不同的谷歌模拟运行相同的谷歌测试用例?
- 谷歌测试方法与流
- _mm256_load_ps调试模式下导致谷歌/基准测试的分段错误
- 谷歌测试:模板模板的笛卡尔乘积的类型列表与模板
- C++ 谷歌测试除以零
- 谷歌风格指南(前向分枝部分)
- 如何在C++中遍历谷歌原型地图?
- 如何更改谷歌原型中的缓冲区限制?
- C++ - 谷歌原型