我希望在Google协议缓冲区中,
有什么简单有效的方法吗? 编辑:如果可能的话,我不想使用任何迭代器来循环遍历所有元素。
repeated field
中只有唯一的元素。换句话说,需要将其用作std::set
而不是std::vector
。有什么简单有效的方法吗? 编辑:如果可能的话,我不想使用任何迭代器来循环遍历所有元素。
repeated field
中只有唯一的元素。换句话说,需要将其用作std::set
而不是std::vector
。RepeatedPtrField< T >*
(列表)和一个std::string
(我们打算添加到列表中的新对象的键),并返回与该id相匹配的元素,如果在RepeatedField
列表中找不到具有此键的条目,则返回NULL
。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;
}
注意:在上面的示例中,proto消息将始终具有名为common
(在我的情况下也是proto消息)的字段。您可以用任何您想要的东西替换它,以便比较您的proto消息。
class Description : public ::google::protobuf::Message {
// ...
inline void add_field(const ::std::string& value);
inline const ::google::protobuf::RepeatedPtrField< ::std::string>& field() const;
// ...
};
我使用了 std::find
来判断列表中是否存在该值,以便仅在该值不存在时添加它:
#include <algorithm>
void addField(Description& description, const std::string& value) {
const auto& fields = description.field();
if (std::find(fields.begin(), fields.end(), value) == fields.end()) {
description.add_field(value);
}
}