我想在 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/