簡體   English   中英

如何將向量添加到重復字段protobuf C ++

[英]How to add vector to repeated field 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

基於使用memcpy將std :: vector復制到protobuf的重復字段中,我執行了以下操作:

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

我究竟做錯了什么?

mutable_proposedsegments()方法返回一個指針,因此開始時可能會缺少* -嘗試使用:

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

另外, std::vector<gen_ProposedSegment>此方法起作用,您需要將輸入鍵入為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 )。

您必須迭代給定的向量並將對象手動添加到protobuf消息中。 您不能為此使用memcpy操作。

以下代碼是我不經測試就寫出來的,但是應該為您指明正確的方向。 順便說一句:我假設在這種情況下, Journeygen_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);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM