2014-09-03 54 views
0

.proto文件結構刪除特定重複字段從谷歌協議緩衝數據

消息repetedMSG { 必需的字符串數據= 1; }

message mainMSG 
{ 
    required repetedMSG_id = 1; 
    repeated repetedMSG rptMSG = 2; 
} 

我有一個mainMSG和在它太多(假設10)repetedMSG都存在。 現在我想從mainMSG中刪除任何特定的repetedMSG(假設第5個repetedMSG)。爲此,我嘗試了3種方法,但都沒有工作。

for (int j = 0; j<mainMSG->repetedMSG_size(); j++){ 
        repetedMSG reptMsg = mainMsg->mutable_repetedMSG(j); 
        if (QString::fromStdString(reptMsg->data).compare("deleteMe") == 0){ 
      *First tried way:-* reptMsg->Clear(); 
      *Second tried Way:-* delete reptMsg; 
      *Third tried way:-* reptMsg->clear_formula_name(); 
         break; 
        } 
       } 

當我序列化mainMSG何時執行該行寫入文件,即我得到運行時錯誤

mainMSG.SerializeToOstream(標準:: fstream的輸出( 「C:/ A /測試1」 ,std :: ios :: out | std :: ios :: trunc | std :: ios :: binary))這裏我得到運行時錯誤

回答

0

您可以使用RepeatedPtrField::DeleteSubrange()這個。但是,要小心在循環中使用這個 - 人們通常這樣寫代碼是O(n^2):

// BAD CODE! O(n^2)! 
for (int i = 0; i < message.foo_size(); i++) { 
    if (should_filter(message.foo(i))) { 
    message.mutable_foo()->DeleteSubrange(i, 1); 
    --i; 
    } 
} 

相反,如果你打算刪除多個元素,做這樣的事情:

// Move all filtered elements to the end of the list. 
int keep = 0; // number to keep 
for (int i = 0; i < message.foo_size(); i++) { 
    if (should_filter(message.foo(i))) { 
    // Skip. 
    } else { 
    if (keep < i) { 
     message.mutable_foo()->SwapElements(i, keep) 
    } 
    ++keep; 
    } 
} 

// Remove the filtered elements. 
message.mutable_foo()->DeleteSubrange(keep, message.foo_size() - keep);