c++ - Protocol Buffer : RepeatedField unique elements

标签 c++ c protocol-buffers

我想在 google protocol buffer repeated field 中只包含唯一元素。换句话说,需要将其用作 std::set 而不是 std::vector

有什么想法是最简单、最有效的方法吗?

编辑:如果可能的话,我不想使用任何迭代器来遍历所有元素。

最佳答案

好的,正如问题的评论所述,不使用迭代器就无法做到这一点。 但是,也许其他人对此感兴趣,这是我为实现此目的而编写的功能。这将作为参数 RepeatedPtrField< T >* (列表)和一个 std::string (我们打算添加到列表中的新对象的键)并将返回与 id 匹配的元素,或 NULL如果在 RepeatedField 中没有包含此键的任何条目列表。

这样,您可以轻松地直接在 RepeatedField 中保留一个唯一元素列表。不使用任何其他 std结构:

template <class T>
T* repeatedFieldLookup( google::protobuf::RepeatedPtrField< T >* repeatedPtrField, std::string id)
{
   google::protobuf::internal::RepeatedPtrOverPtrsIterator<T> it = repeatedPtrField->pointer_begin();
   for ( ; it != repeatedPtrField->pointer_end() ; ++it )
   {
      CommonFields * commonMessage = (CommonFields*) (*it)->GetReflection()->
     MutableMessage ((*it), (*it)->GetDescriptor()->FindFieldByName ("common"));
      if(commonMessage->id() == id)
      {
     return *it;
      }
   }
   return NULL;
}

注意:在上面的示例中,原型(prototype)消息将始终有一个名为 common 的字段(在我的例子中也是一个原型(prototype)消息)。您可以将其替换为您想要从原始消息中进行比较的任何内容。

关于c++ - Protocol Buffer : RepeatedField unique elements,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15880086/

相关文章:

c++ - Protocol Buffers C++ 中的异常处理

c++ - 链接 SDL2 与 CMake

c++ - 如何强制所有派生类实现虚方法?

c - fscanf() 只读取一条记录,忽略其余记录

两个指针变量可以指向同一个内存地址吗?

Java 和谷歌 Protocol Buffer : Does anyone have a simple example of getting started with this?

c++ - 为什么后增需要复制,而前增不需要

c++ - 为什么 while 循环会无限重复?

c - 函数应该有原型(prototype)错误

protocol-buffers - protobuffers 中的重复字段是否保持插入的顺序?