2016-03-01 45 views
0

是這樣的:擦除元素,載體與結構填充

struct mystruct 
{ 
    char straddr[size]; 
    int port; 
    int id; 
    ....... 
}; 

mystruct s1={......}; 
mystruct s2={......}; 
mystruct s3={......}; 

vector test; 
test.emplace_back(s1); 
test.emplace_back(s2); 
test.emplace_back(s3); 

現在我想刪除與straddr =「ABC」和端口元= 1001 我應該怎麼辦? 而我不想這樣做。

所有的
for(auto it = test.begin();it != test.end();) 
    { 
     if(it->port == port && 0 == strcmp(it->straddr,straddr)) 
     it = test.erase(it); 
    else 
     it++; 
    } 
+1

這聽起來像是我的一項家庭作業 – HairOfTheDog

+0

@ barq,@ HairOfTheDog我試着用for循環。但我認爲這是愚蠢的。 – Atlantis

回答

3

首先,使用的std::string代替char [size],這樣就可以使用==代替strcmp等這樣的C-字符串函數。

然後用std::remove_if()沿erase()爲:

test.erase (
    std::remove_if(
     test.begin(), 
     test.end(), 
     [](mystruct const & s) { 
      return s.port == 1001 && s.straddr == "abc"; 
     } 
    ), 
    test.end() 
); 

這是慣用的解決你的問題,你可以在這裏閱讀更多關於它:

注意此解決方案將從容器中移除預測返回的所有元素。但是,如果事先知道將有最多一個項目相匹配的謂詞,然後用std::find_if伴隨erase()將會更快:

auto it = std::find_if(
      test.begin(), 
      test.end(), 
      [](mystruct const & s) { 
       return s.port == 1001 && s.straddr == "abc"; 
      } 
     ); 
if(it != test.end())//make sure you dont pass end() iterator. 
    test.erase(it); 

希望有所幫助。

+1

謝謝,這非常有用。 – Atlantis

+1

erase/remove_if是一種很好的共享技巧,但問題確實會說*「想要刪除元素」* - 如果不是不小心使用了「the」,並且已知最多隻有一個匹配,那麼find_if和有針對性的「擦除」會更快。 –

+0

@TonyD:我也考慮過這種解釋的可能性,但後來我在問題中看到了* for *循環,所以我提出了一個等效的解決方案。 – Nawaz