2016-03-01 44 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