[英]What is the most efficient way to get all elements from a ProtoBuf RepeatedField?
[英]protobuf: RepeatedField unique elements
我想在Google協議緩沖區中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;
}
注意 :在上面的示例中,原始消息將始終具有一個稱為common
的字段(在我的情況下,這也是原始消息)。 您可以將其替換為要與原始消息進行比較的任何內容。
在我上這節課的情況下:
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);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.