C++ iterator to access repeated elements.

10,766 views
Skip to first unread message

Alex Shaver

unread,
Jun 29, 2016, 2:58:25 PM6/29/16
to Protocol Buffers
(proto3)

Suppose I have some message with a repeated submessage element; especially given c++11's for range operator and other iterator-type algorithms, it feels like there should be iterator access to the submessages, beyond just the 'index' based approach.

I may be missing the fact that it does exist somewhere (the c++ documentation isn't up to date, really), or that there's other c++ limitations (these submessages are stored in some way that iterator access is prohibitively difficult/impossible). Otherwise, it definitely seems like an important element in the modern c++ styles.

Feng Xiao

unread,
Jun 29, 2016, 3:13:39 PM6/29/16
to Alex Shaver, Protocol Buffers
Suppose you have the following proto definition:

message Foo {
  repeated Foo children = 1;
}

You should be able to write code like:

Foo foo = ...;
for (const Foo& child : foo.children()) {
  ...
}
 

--
You received this message because you are subscribed to the Google Groups "Protocol Buffers" group.
To unsubscribe from this group and stop receiving emails from it, send an email to protobuf+u...@googlegroups.com.
To post to this group, send email to prot...@googlegroups.com.
Visit this group at https://groups.google.com/group/protobuf.
For more options, visit https://groups.google.com/d/optout.

Alex Shaver

unread,
Jun 30, 2016, 9:25:41 AM6/30/16
to Protocol Buffers, alexs...@gmail.com
Ah, that's what I missed. The 'children' element is a 'RepeatedField' type which has the associated iterators. Thanks for the help.

Alex Shaver

unread,
Jun 30, 2016, 9:45:03 AM6/30/16
to Protocol Buffers, alexs...@gmail.com
Edit: just as a for instance:

suppose:
in proto file:
message Foo{
  repeated
double values = 1;
}

in .cpp:

Foo protobuf;
protobuf
.add_values(1.23);
protobuf
.add_values(3.45);
protobuf
.add_values(6.78);
std
::vector<double> outVector{0,0,0};
std
::transform(protobuf.values().cbegin(), protobuf.values().cend(), outVector.begin(), [](const double& in){return in + 1.5;});
std
::vector<double> expectedVector{2.73, 4.95, 8.28};
ASSERT_EQ
(expectedVector, outVector);

will be a successful test.
Reply all
Reply to author
Forward
0 new messages