简体   繁体   English

从向量中擦除元素,然后向量中填充struct

[英]Erase element from vector,and the vector is fill with struct

something like this: 像这样的东西:

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);

now i want to erase the element with straddr="abc" and port = 1001. what should i do? 现在我想用straddr =“ abc”和port = 1001删除元素。我该怎么办? And i don't want to do it like this. 而且我不想这样。

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

First of all, use std::string instead of char [size] so that you can use == instead of strcmp and other such c-string functions. 首先,使用std::string代替char [size]以便可以使用==代替strcmp和其他类似的c-string函数。

Then use std::remove_if() along with erase() as: 然后将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()
);

It is idiomatic solution to your problem and you can read more about it here: 这是解决您的问题的惯用方法,您可以在这里阅读有关它的更多信息:

Note that this solution will remove all elements from the container for which the predicated returns true . 请注意,此解决方案将从谓词返回true的容器中删除所有元素。 However, if it is known in advance that there will be at most one item matching the predicate, then std::find_if accompanied with erase() would be faster: 但是,如果事先知道最多有一个与谓词匹配的项,则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); 

Hope that helps. 希望能有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM