如何将向量添加到重复字段protobuf C ++

时间:2018-10-10 12:28:10

标签: c++ protobuf-c

我有以下protobuf消息:

message gen_Journey {
  repeated gen_ProposedSegment proposedSegments = 1;
}

生成的cpp如下

// repeated .gen_ProposedSegment proposedSegments = 1;
int gen_Journey::proposedsegments_size() const {
  return proposedsegments_.size();
}
void gen_Journey::clear_proposedsegments() {
  proposedsegments_.Clear();
}
const ::gen_ProposedSegment& gen_Journey::proposedsegments(int index) const {
  // @@protoc_insertion_point(field_get:gen_Journey.proposedSegments)
  return proposedsegments_.Get(index);
}
::gen_ProposedSegment* gen_Journey::mutable_proposedsegments(int index) {
  // @@protoc_insertion_point(field_mutable:gen_Journey.proposedSegments)
  return proposedsegments_.Mutable(index);
}
::gen_ProposedSegment* gen_Journey::add_proposedsegments() {
  // @@protoc_insertion_point(field_add:gen_Journey.proposedSegments)
  return proposedsegments_.Add();
}
::google::protobuf::RepeatedPtrField< ::gen_ProposedSegment >*
gen_Journey::mutable_proposedsegments() {
  // @@protoc_insertion_point(field_mutable_list:gen_Journey.proposedSegments)
  return &proposedsegments_;
}
const ::google::protobuf::RepeatedPtrField< ::gen_ProposedSegment >&
gen_Journey::proposedsegments() const {
  // @@protoc_insertion_point(field_list:gen_Journey.proposedSegments)
  return proposedsegments_;
}

我创建了以下向量:

std::vector<gen_ProposedSegment *> proposedSegment

基于Copy a std::vector to a repeated field from protobuf with memcpy,我执行了以下操作:

Journey::Journey(std::vector<gen_ProposedSegment *> proposedSegment) {
    this->mutable_proposedsegments() = {proposedSegment.begin(), proposedSegment.end()};
}

问题是我遇到以下错误:

/home/compilation/UnixPackagesFareShopping/src/DOM/src/journey.cpp:10:35: error: lvalue required as left operand of assignment

我在做什么错?

2 个答案:

答案 0 :(得分:2)

mutable_proposedsegments()方法返回一个指针,因此开始时可能会缺少*-请尝试:

Journey::Journey(std::vector<gen_ProposedSegment *> proposedSegment) {
    *this->mutable_proposedsegments() = {proposedSegment.begin(), proposedSegment.end()};
}

此外,要执行此操作,您需要将输入键入为std::vector<gen_ProposedSegment>(最好使用const ref),即:

Journey::Journey(const std::vector<gen_ProposedSegment>& proposedSegment) {
    *this->mutable_proposedsegments() = {proposedSegment.begin(), proposedSegment.end()};
}

或者,您需要将这些项目插入for循环中(请参见std::for_each)。

答案 1 :(得分:1)

您必须迭代给定的向量并将对象手动添加到protobuf消息中。您不能为此使用memcpy操作。

下面的代码是我不经测试就写出来的,但是应该指出正确的方向。顺便说一句:我假设Journey在这种情况下是从gen_Journey继承的。否则,您必须相应地调整“ this->”语句。

Journey::Journey(const std::vector<gen_ProposedSegment *> &proposedSegment) {
    auto copy = [&](const gen_ProposedSegment *) {
        auto temp_seg = this->add_proposedsegments();
        temp_seg->CopyFrom(*gen_ProposedSegment);
    };
    std::for_each(proposedSegment.cbegin(), proposedSegment.cend(), copy);
}