Grégoire Borel
Grégoire Borel

Reputation: 2028

Compare two Repeated Fields with the C++ API

Let's say I have two instances of the following protobuf structure:

message customStruct
{
    optional int32  a = 1;
    optional int32  b = 2;
}

message info
{
    repeated customStruct  cs = 1;
    optional int32         x = 2;
    optional double        y = 3;
}

message root
{
    optional info inf =  1;
}

I know I can compare Messages with the C++ API but I would like to directly compare two Repeated Fields (customStruct here), for simplicity and perhaps performance optimization.

Ideally, I would need a C++ equivalent of the C# method Equals(RepeatedField< T > other).

Is that feasible in C++? Is it a good practice?

Upvotes: 5

Views: 2265

Answers (2)

hasdrubal
hasdrubal

Reputation: 1148

To augment @jdehesa's answer:

#include <algorithm>
#include <...>

const google::protobuf::ReapeatedField<int32> & myField1 = ...;
const google::protobuf::ReapeatedField<int32> & myField2 = ...;
bool fieldsEqual = std::equal(myField1.begin(), myField1.end(), myField2.begin(), 
google::protobuf::utils::MessageDifferencer::Equals);

Upvotes: -1

javidcf
javidcf

Reputation: 59701

RepeatedField<T> has STL-like iterators, so you can use std::equal to compare them:

#include <algorithm>
#include <...>

const google::protobuf::ReapeatedField<int32> & myField1 = ...;
const google::protobuf::ReapeatedField<int32> & myField2 = ...;
bool fieldsEqual = std::equal(myField1.begin(), myField1.end(), myField2.begin());

Upvotes: 4

Related Questions