Atlantis
Atlantis

Reputation: 1

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? 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++;
   }

Upvotes: 0

Views: 123

Answers (1)

Sarfaraz Nawaz
Sarfaraz Nawaz

Reputation: 361612

First of all, use std::string instead of char [size] so that you can use == instead of strcmp and other such c-string functions.

Then use std::remove_if() along with erase() as:

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. 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:

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.

Upvotes: 3

Related Questions