c++ - Erase element from vector,and the vector is fill with struct -
something 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 want erase element straddr="abc" , port = 1001. should do? , don't want this.
for(auto = test.begin();it != test.end();) { if(it->port == port && 0 == strcmp(it->straddr,straddr)) = test.erase(it); else it++; }
first of all, use std::string
instead of char [size]
can use ==
instead of strcmp
, other such c-string functions.
then use std::remove_if()
along erase()
as:
test.erase ( std::remove_if( test.begin(), test.end(), [](mystruct const & s) { return s.port == 1001 && s.straddr == "abc"; } ), test.end() );
it idiomatic solution problem , can read more here:
note solution remove elements container predicated returns true
. however, if known in advance there @ 1 item matching predicate, std::find_if
accompanied erase()
faster:
auto = std::find_if( test.begin(), test.end(), [](mystruct const & s) { return s.port == 1001 && s.straddr == "abc"; } ); if(it != test.end())//make sure dont pass end() iterator. test.erase(it);
hope helps.
Comments
Post a Comment